从另一个表对嵌套的SELECT执行NOT IN时查询很慢

时间:2009-10-26 07:48:47

标签: sql mysql

SELECT problems . * , users.id AS new_user_id, users.nick AS nick
FROM problems, users
WHERE problems.deleted =0
AND problems.topic_id =1
AND problems.user_id = users.id
AND problems.id NOT
IN (
  SELECT DISTINCT (problem_id)
  FROM problems_attempted
  WHERE user_id =1
  AND total_questions = ( attempted_right + attempted_wrong + skipped )
)
ORDER BY problems.updated DESC

可以优化此查询以获得更好的性能吗?

1 个答案:

答案 0 :(得分:3)

嵌套查询始终是性能瓶颈。尝试使用连接

select p.*, u.* 
from problems p join users u 
on p.user_id = u.id 
join problems_attempted pa on pa.problem_id = p.id 
where not (pa.user_id = 1 
and total_questions = ( attempted_right + attempted_wrong + skipped ))