簡體   English   中英

如何向此查詢添加其他條件(使用CASE)?

[英]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'flagged0

基於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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM