是否有更快的方法来计算连接上的记录

时间:2009-11-16 13:02:15

标签: sql mysql

当个人资料是演员时,此查询会获取具有最多证据记录的个人资料。 有没有办法让它在mysql查询中更快?

SELECT profiles.*, count(*) AS counted_profiles 
FROM `profiles` 
INNER JOIN (SELECT ev.actor_id 
            FROM evidences AS ev 
            WHERE ev.actor_type = 'Profile') AS ev2
ON ev2.actor_id = profiles.id 
GROUP BY ev2.actor_id 
ORDER BY counted_profiles DESC LIMIT 10

2 个答案:

答案 0 :(得分:4)

您可以删除profiles.*,删除子选择,并为连接字段添加索引。

另外,请考虑一下:

SELECT ev.actor_id, count(*) AS counted_profiles 
FROM `profiles` INNER JOIN evidences AS ev
      ON ev.actor_id = profiles.id AND ev.actor_type = 'Profile'
GROUP BY ev.actor_id 
ORDER BY counted_profiles DESC LIMIT 10

答案 1 :(得分:0)

您可以在子查询中使用GROUP BY,ORDER BY和LIMIT子句,然后使用INNER JOIN。 这只是另一种方式,但不确定性能增益。