简体   繁体   English

SQL多重选择…其中id和DISTINCT

[英]SQL multiple Select … where id in and a DISTINCT

I am running a query with multiple "where id in" clauses on a table in a MySQL db. 我正在一个MySQL数据库中的表上运行带有多个“ where id in”子句的查询。 I put DISTINCT in each query to try to cut down the number of results. 我将DISTINCT放在每个查询中以尝试减少结果数。 Still locked up my MySQL table. 仍然锁定了我的MySQL表。 Any glitches I don't know about, or should I try getting rid of some of the DISTICTs? 我不知道的任何故障,还是应该尝试摆脱一些DISTICT? Only the first DISTINCT is necessary. 只需要第一个DISTINCT。

   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. 最后一个表TP_Student_Answers具有约32,000个条目。 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? 还有其他问题吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM