我使用表格Votes
存储用户帖子的喜欢/不喜欢(Posts
)。现在我想选择喜欢和不喜欢的帖子的数量。目前查询如下:
SELECT p.*, count(v1.id) AS Likes, count(v2.id) AS Dislikes FROM Posts p
LEFT JOIN Votes v1 ON v1.post_id=p.id AND v1.status=1
LEFT JOIN Votes v2 ON v2.post_id=p.id AND v2.status=2
WHERE p.id=123
有两种情况可以合并为一种更好的方法吗?
答案 0 :(得分:1)
您可以在一个CASE
SUM
和JOIN
像
这样的东西SELECT p.*,
SUM(CASE WHEN v1.status=1 THEN 1 ELSE 0 END) AS Likes,
SUM(CASE WHEN v1.status=2 THEN 1 ELSE 0 END) AS Dislikes FROM Posts p
LEFT JOIN Votes v1 ON v1.post_id=p.id
WHERE p.id=123