Question

I am running a query with multiple "where id in" clauses on a table in a MySQL db. I put DISTINCT in each query to try to cut down the number of results. Still locked up my MySQL table. Any glitches I don't know about, or should I try getting rid of some of the DISTICTs? Only the first DISTINCT is necessary.

   SELECT DISTINCT id, name 
   FROM TP_Test_Info 
   WHERE id IN (SELECT DISTINCT test_id 
                FROM TP_Test_Sections 
                WHERE id IN (SELECT DISTINCT section_id 
                             FROM TP_Test_Questions 
                             WHERE id IN (SELECT DISTINCT question_id 
                                          FROM TP_Student_Answers 
                                          WHERE student_id = 751)))

The last table TP_Student_Answers has about 32,000 entries. The rest are much smaller.

I realized that I should have indexed some of the rows in the big table. Spaced it. Any other problems stick out?

Was it helpful?

Solution

You should be using joins and consider creating indexes at least on foreign keys

Try the following

SELECT DISTINCT TP_Test_Info.id, TP_Test_Info.name
FROM TP_Test_Info
JOIN TP_Test_Sections 
  ON TP_Test_Sections.test_id = TP_Test_Info.id
JOIN TP_Test_Questions 
  ON TP_Test_Questions.section_id = TP_Test_Sections.id
JOIN TP_Student_Answers 
  ON TP_Student_Answers.question_id = TP_Test_Questions.id
WHERE TP_Student_Answers.student_id = 751
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top