如何为此查询添加其他条件(使用CASE)?

时间:2009-09-08 17:16:48

标签: mysql conditional case

到目前为止,这是我的查询:

  

选择
          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}},但这会导致致命错误。我怎样才能做到这一点?

谢谢!

3 个答案:

答案 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

由于您只对commentsstatus的{​​{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