慢MySQL查询:有没有办法避免对左连接的每一行进行条件选择计数?

时间:2014-03-26 06:23:01

标签: mysql performance left-join database-performance query-performance

表格
视频:id
评级:id,video_id,user_id,评级

每个视频可以有多个评分。视频表有10,000多行。某些视频可能还没有与之相关的任何评分数据。

我想选择特定用户(本例中为user_id 1)尚未评级的所有视频。

查询:

SELECT 
    videos.id, 
    (SELECT count(id) FROM ratings WHERE user_id = 1 AND ratings.video_id = videos.id) 
    AS rating_count    
FROM videos   
LEFT JOIN ratings ON ratings.video_id = videos.id  
GROUP BY videos.id  
HAVING rating_count = 0  
ORDER BY ratings.rating DESC   
LIMIT 20

查询每次至少需要4秒钟。我可能不应该在这里使用左连接吗?

1 个答案:

答案 0 :(得分:1)

您可以删除子查询并重写您的查询,如下所示,您也可以在加入的on子句中使用用户ID AND ratings.user_id = 1条件,这样即使所有视频与该用户无关,也会返回所有视频

SELECT 
    videos.id, 
    count(ratings.id)  AS rating_count    
FROM videos   
LEFT JOIN ratings 
ON (ratings.video_id = videos.id   AND ratings.user_id = 1)
GROUP BY videos.id  
HAVING rating_count = 0  
ORDER BY ratings.rating DESC   
LIMIT 20