我有一个子查询的查询应该是快速的,而不是它非常慢。任何人都可以建议让MySQL正常运行的方法吗?
使用MySQL服务器版本:5.5.41 MySQL社区服务器(GPL)
执行合并查询:
Explain SELECT * FROM StudySpecSubject WHERE SubjectID IN (
SELECT SubjectID FROM StudySpecSubject WHERE SpecimenID ='123456');
id select_type table type possible_keys key key_len ref rows Extra
--- ------------------- ---------------- ---------- --------------- ------- ------- ---------- -------- ------------------------
1 PRIMARY StudySpecSubject ALL <null> <null> <null> <null> 14015412 Using where
2 DEPENDENT SUBQUERY StudySpecSubject index_subq Subject,rlimsID Subject 66 func,const 1 Using index; Using where
执行与两个单独查询完全相同的查询:
Explain SELECT SubjectID FROM StudySpecSubject WHERE SpecimenID ='123456';
Explain SELECT * FROM StudySpecSubject WHERE SubjectID IN ('AB-CDEF');
id select_type table type possible_keys key key_len ref rows Extra
--- ------------------- ---------------- ---- ------------- ------- ------- ----- ---- -----------
1 SIMPLE StudySpecSubject ref rlimsID rlimsID 33 const 1 Using where
id select_type table type possible_keys key key_len ref rows Extra
--- ------------------- ---------------- ---- ------------- ------- ------- ----- ---- -----------
1 SIMPLE StudySpecSubject ref Subject Subject 33 const 52 Using where
表格定义:
CREATE TABLE `StudySpecSubject` (
StudyID VarChar(31) NOT NULL,
SubjectID VarChar(31) NOT NULL,
SpecimenID VarChar(31) NOT NULL,
which Int unsigned NOT NULL,
INDEX Study (StudyID, SubjectID, SpecimenID),
INDEX Subject (SubjectID, SpecimenID),
INDEX rlimsID (SpecimenID),
INDEX byTable (which)
) ENGINE = INNODB DEFAULT CHARSET=latin1;
答案 0 :(得分:3)
在一些WHERE IN (SELECT ...)
查询中,MySQL出了名。最好将它们写成JOIN
。
SELECT t1.*
FROM StudySpecSubject AS t1
JOIN StudySpecSubject AS t2 ON t1.SubjectID = t2.SubjectID
WHERE t2.SpecimenID = '123456'
MySQL的错误是,它不是从子查询中获取所有主题ID,而是使用它来索引表,它会扫描主查询中的整个表,然后执行子查询来测试主题ID是否在退回的表。