0

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

SELECT
posts.title
, SUM(CASE comments.status WHEN 'approved' THEN 1 END) 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

我需要让它在它得到时也检查comment.flagged= 0 commentsCount。我尝试CASESUM()调用中添加额外的 s,但这导致了致命错误。我怎样才能做到这一点?

谢谢!

4

3 回答 3

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
于 2009-09-08T17:23:45.390 回答
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

由于您只对commentswho statusis感兴趣'approved',因此条件应该是 join 条件。

编辑:我已经更新了查询,假设您想要计算status等于'approved'flagged等于的评论0

于 2009-09-08T17:34:13.450 回答
0

基于 Josh Davis 的 SQL,这对我有用:

SELECT
posts.title
, posts.slug
, COUNT(comments.id) 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

于 2009-09-08T17:45:19.543 回答