【发布时间】:2022-10-14 22:41:54
【问题描述】:
我有这两个表:
tblCommentReactions
| id | Liked | CommentID |
|---|---|---|
| 1 | 0 | 1 |
| 2 | 1 | 1 |
| 3 | 1 | 1 |
| 4 | 0 | 2 |
1是喜欢,0是不喜欢。
tbl评论:
| id | userID | message |
|---|---|---|
| 1 | 1 | message 1 |
| 2 | 1 | message 2 |
| 3 | 2 | message 1 |
我尝试选择所有 cmets 并计算不喜欢和喜欢并在同一行中给出结果。
SELECT c.ID as CommentID, c.message,
COUNT(case when Liked = 1 AND r.CommentID = c.ID then 1 else null end) as likes,
COUNT(case when Liked = 0 AND r.CommentID = c.ID then 1 else null end) as dislikes
FROM tblcomments as c LEFT JOIN tblcommentreactions as r ON c.ID = r.CommentID
WHERE c.userID = 1;
预期输出应该是:
| CommentID | message | likes | dislikes |
|---|---|---|---|
| 1 | message 1 | 2 | 1 |
| 2 | message 2 | 0 | 1 |
在我的 Return 上,它会计算所有内容,并且只返回第一条消息。你能告诉我我需要改变我的请求,以获得我的预期输出吗?
【问题讨论】:
-
您使用的是哪个 RDBMS?我猜是 MySQL,因为如果没有
GROUP BY c.ID, c.message(或者有时是GROUP BY c.ID),大多数 RDBMS 都不会允许这样做。 -
在您的案例语句“AND r.CommentID = c.ID”中是多余的,因为它由 LEFT JOIN 处理。您也可以使用 ELSE 0 因为它在 COUNT 函数中
标签: sql