优化多个 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。
感谢您的任何回复!
编辑:为了说清楚:我希望它返回一行两列; 赞成票
和反对票
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>
Straight up question; how could this be optimized? I can't think of any better way to do it but I'm bad at MySQL.
Thanks for any responses!
EDIT: To make things clear: I want it to return one row with two columns; upvotes
and downvotes
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
尝试使用 SUM 而不是 COUNT:
请注意,这不会为您提供与您发布的查询相同的结果。我认为您发布的查询错误!
Try using SUM instead of COUNT:
Note that this does not give you the same result as the query you posted. I think the query you posted is wrong!
我会用这个:
I would be using this:
是时候学习了:
count
只计算非空值,因此每当您看到then 1
时,也可能是then 'Yay!'
。空值不计算在内。Time to learn:
count
only counts non-nulls, so whenever you seethen 1
might as well bethen 'Yay!'
. Nulls are not counted.恕我直言,您根本不应该计算飞行中的总票数。相反,您应该将总投票数与项目一起存储,并使用详细的投票日志作为确保结果完整性的工具,并让用户能够撤回投票。
IMHO , you should not be calculating the total vote count on a fly at all. Instead you should store the total vote count with the item, and use the detailed vote log as a tool for ensuring the integrity of to results and give the users ability to withdraw the vote.
我想所有评论者的意思是你的查询可能应该是:
到目前为止,你至少有 4 种其他方法与此方法相同(3 种方法与此完全相同,1 种方法略有不同,给出相同的结果,但在 2 行中)。使用您的数据进行测试并选择更快的数据(或者保留所有数据,并在表变大时再次测试)。
(link,vote)
上的复合索引对于所有版本也很有用。I guess all commentors meant that your query should probably be:
By now, you have at least 4 other ways that do the same as this one (3 ways exactly this and 1 way slightly different, giving the same results but in 2 rows). Test with your data and choose the faster (or keep them all and test again later, when the table grows bigger).
A composite index on
(link,vote)
would also be useful for all versions.