优化多个SELECT

时间:2011-10-17 20:16:43

标签: mysql sql optimization select

SELECT 
  (SELECT COUNT(*) FROM votes WHERE votes.vote = 1) AS upvotes,
  (SELECT COUNT(*) FROM votes WHERE votes.vote = -1) AS downvotes,
FROM votes WHERE link = <linkid>

直截了当的问题;怎么可以优化?我想不出更好的方法,但我对MySQL不好。

感谢您的回复!

编辑:为了清楚起见:我希望它返回一行有两列; upvotesdownvotes

6 个答案:

答案 0 :(得分:3)

SELECT sum(case when vote = 1 then 1 end) as upvotes,
    sum(case when vote = -1 then 1 end) as downvotes
FROM votes
WHERE link = < linkid >

答案 1 :(得分:2)

尝试使用SUM而不是COUNT:

SELECT 
  SUM(vote = 1) AS upvotes,
  SUM(vote = -1) AS downvotes
FROM votes WHERE link = <linkid>

请注意,会为您提供与您发布的查询相同的结果。我认为您发布的查询错误

答案 2 :(得分:1)

我会用这个:

SELECT COUNT(*), vote AS numvotes FROM votes WHERE vote = -1 OR vote = 1 GROUP BY vote

答案 3 :(得分:1)

SELECT 
  COUNT(case vote when  1 then 1 else null end) AS upvotes,
  COUNT(case vote when -1 then 1 else null end) AS downvotes
FROM votes WHERE link = <linkid>

学习时间:count仅计算非空值,因此每当您看到then 1也可能是then 'Yay!'时。空值不计算在内。

答案 4 :(得分:1)

我猜所有评论员都认为您的查询应该是:

SELECT 
  (SELECT COUNT(*) FROM votes WHERE link = <linkid> AND vote = 1 ) AS upvotes,
  (SELECT COUNT(*) FROM votes WHERE link = <linkid> AND vote = -1) AS downvotes

到目前为止,您至少有4种其他方式与此方法相同(3种方式完全相同,1种方式稍有不同,给出相同的结果,但是在2行中)。使用您的数据进行测试并选择更快(或保留所有数据并稍后再次测试,当表变大时)。

(link,vote)上的复合索引对所有版本都有用。

答案 5 :(得分:1)

恕我直言,你不应该计算苍蝇的总投票数 。相反,您应该将总投票数与商品一起存储,并使用详细的投票日志作为确保结果完整性的工具,并让用户有权撤回投票。