我有这个:
SELECT
posts.id,
(SELECT COUNT(*) FROM votes WHERE votes.post = posts.id) AS votesCount,
(SELECT SUM(vote) FROM votes WHERE votes.post = posts.id) AS votesUp
FROM posts WHERE posts.id = 1
如何在不执行其他SELECT的情况下获得 votesCount 和 votesUp 之间的区别?类似的东西:
SELECT
posts.id,
(SELECT COUNT(*) FROM votes WHERE votes.post = posts.id) AS votesCount,
(SELECT SUM(vote) FROM votes WHERE votes.post = posts.id) AS votesUp,
votesCount - votesUp AS votesDown
FROM posts WHERE posts.id = 1
是否可能,或者我是否必须再拨打另一个SELECT? 感谢。
是的,抱歉我的英语不好。答案 0 :(得分:3)
我建议您加入投票而不是使用子查询,然后您可以轻松地重复使用聚合:
select
p.id,
count(v.post) as votesCount,
sum(v.vote) as votesUp,
count(v.post) - sum(v.vote) as votesDown
from
posts p
left join votes v on v.post = p.id
where
p.id = 1
group by
p.id
答案 1 :(得分:1)
您的子查询不太有意义。通常,您希望使用子查询作为最后的手段,而不是连接。例如:
SELECT
posts.id, COUNT(votes.*) AS votesCount, SUM(vote) AS votesUp
FROM posts
LEFT JOIN votes ON votes.post = posts.id
WHERE
posts.id = 1
GROUP BY posts.id
这也使得减法更容易,但遗憾的是它需要一些重复(别名不能用于后续列:/):
SELECT
posts.id, COUNT(votes.*) AS votesCount, SUM(vote) AS votesUp,
COUNT(votes.id) - SUM(vote) AS votesDown
FROM posts
LEFT JOIN votes ON votes.post = posts.id
WHERE
posts.id = 1
GROUP BY posts.id
答案 2 :(得分:-3)
甚至没有另一个嵌套的SELECT?
SELECT
posts.id,
(SELECT COUNT(*) FROM votes WHERE votes.post = posts.id) AS votesCount,
(SELECT SUM(vote) FROM votes WHERE votes.post = posts.id) AS votesUp
(SELECT SUM(CASE WHEN vote=0 THEN 1 ELSE 0 END) FROM votes WHERE votes.post = posts.id) AS votesDown
FROM posts WHERE posts.id = 1