[英]How can I add an additional condition to this query (using CASE)?
到目前为止,这是我的查询:
选择
posts.title
,SUM(“批准” THEN 1 END时为CASE comments.status)为commentsCount
来自帖子
内联接评论
开启comments.postID = posts.id
哪里
posts.status =?
通过...分组
posts.title
订购
计数DESC
极限5
我还需要在获取commentsCount
时检查comment.flagged
= 0。 我尝试在SUM()
调用中添加其他CASE
,但这导致了致命错误。 我该如何实现?
谢谢!
SELECT
posts.title
, SUM(IF ((comments.status='approved' AND comments.flagged = 0),1,0)) AS commentsCount
FROM posts
INNER JOIN comments
ON comments.postID = posts.id
WHERE
posts.status = ?
GROUP BY
posts.title
ORDER BY
commentsCount DESC
LIMIT 5
似乎您真正想要做的是:
SELECT
posts.title
, COUNT(*) AS commentsCount
FROM posts
INNER JOIN comments
ON comments.postID = posts.id
AND comments.status = 'approved'
AND comments.flagged = 0
WHERE
posts.status = ?
GROUP BY
posts.title
ORDER BY
commentsCount DESC
LIMIT 5
由于您仅对status
为'approved'
comments
感兴趣,因此条件应为联接条件。
编辑:我已更新查询,假设您要计算status
为'approved'
且flagged
为0
。
基于Josh Davis的SQL,这对我有用:
选择
posts.title
,posts.slug
,COUNT(comments.id)个AS评论数
来自帖子
内联接评论
开启comments.postID = posts.id
AND comments.status ='已批准'
AND comments.flagged = 0
哪里
posts.status =?
通过...分组
posts.title
订购
计数DESC
极限5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.