I have a mysql table with the following columns:
id (autoincremented primary key)
user_id
test_id
test_score
How can I get all test data tied to the users that have participated in test_id = 5. I want all test data (not just test_id 5) for the users that have participated in that particular test.
Sounds like you’d want to do a self-join. Something like this would utilize indexes (assuming you have an index on
user_idand an index ontest_id, which you should):I guess that raises another point. How is your table indexed? Just the numeric primary key? You generally want to have indexes on all columns that are used in JOINs or WHERE clauses. Thus, you’d want to have an index on
user_idand an index ontest_id.Can a user take the same test multiple times? If not, then you’d want restrict that by having a unique multiple-column (“composite”) index across
user_idandtest_idtogether. And then add a regular index just totest_idfor the WHERE clause.