到目前为止,这是我的查询:
选择
posts.title
,SUM(CASE comments.status WHEN'批准'那么1结束)作为commentsCount
来自帖子
INNER JOIN评论
ON comments.postID = posts.id
WHERE
posts.status =?
GROUP BY posts.title
订购单 commentsCount DESC
限制5
我需要让它在comment.flagged
获得commentsCount
时检查CASE
= 0。我尝试在SUM()
调用中添加其他{{1}},但这会导致致命错误。我怎样才能做到这一点?
谢谢!
答案 0 :(得分:1)
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
答案 1 :(得分:1)
看起来你真正想做的就是:
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
由于您只对comments
为status
的{{1}}感兴趣,因此条件应处于加入条件。
编辑:我已更新了该查询,假设您要计算'approved'
为status
且'approved'
等于flagged
的评论。
答案 2 :(得分:0)
基于Josh Davis的SQL,这对我有用:
选择
posts.title
,posts.slug
,COUNT(comments.id)AS commentsCount
来自帖子
INNER JOIN评论
ON comments.postID = posts.id
AND comments.status ='已批准' AND comments.flagged = 0
WHERE
posts.status =?
GROUP BY posts.title
订购单 commentsCount DESC
限制5