avi*_*viv 3 mysql sql database performance
我有一个查询从另一个子查询选择中进行选择.虽然两个查询看起来几乎相同,但第二个查询(在此示例中)运行速度要慢得多:
SELECT
user.id
,user.first_name
-- user.*
FROM user
WHERE
user.id IN (SELECT ref_id
FROM education
WHERE ref_type='user'
AND education.institute_id='58'
AND education.institute_type='1'
);
Run Code Online (Sandbox Code Playgroud)
此查询需要1.2s解释此查询结果:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY user index first_name 152 141192 Using where; Using index
2 DEPENDENT SUBQUERY education index_subquery ref_type,ref_id,institute_id,institute_type,ref_type_2 ref_id 4 func 1 Using where
Run Code Online (Sandbox Code Playgroud)
第二个查询:
SELECT
-- user.id
-- user.first_name
user.*
FROM user
WHERE
user.id IN (SELECT ref_id
FROM education
WHERE ref_type='user'
AND education.institute_id='58'
AND education.institute_type='1'
);
Run Code Online (Sandbox Code Playgroud)
需要45秒才能运行,并解释:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY user ALL 141192 Using where
2 DEPENDENT SUBQUERY education index_subquery ref_type,ref_id,institute_id,institute_type,ref_type_2 ref_id 4 func 1 Using where
Run Code Online (Sandbox Code Playgroud)
如果我只通过索引字段查询,为什么它会变慢?为什么两个查询都扫描用户表的全长?任何想法如何改进?
谢谢.
我不确定为什么当你只选择两列时它选择使用索引但是当你选择所有列时不选择使用索引,但最好只选择你需要的列.尝试JOIN而不是子查询可能更好:
SELECT
user.id
user.first_name
FROM user
JOIN education
ON user.id = education.ref_id
AND education.ref_type='user'
AND education.institute_id='58'
AND education.institute_type='1'
Run Code Online (Sandbox Code Playgroud)