2009-09-08 71 views
0

這裏是我的查詢到目前爲止:如何爲此查詢添加附加條件(使用CASE)?

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。我嘗試在SUM()調用中添加其他CASE s,但這導致了一個致命錯誤。我怎樣才能做到這一點?

謝謝!

回答

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'approved',病情應該在連接條件感興趣。

編輯:我已經更新了查詢假設你要計算其評論爲status'approved'flagged等於0

+0

我需要獲取已批准和懸掛本國國旗的專欄評論= 0,我想你的SQL,並得到這個錯誤信息:「您的SQL語法錯誤;檢查對應於你的MySQL服務器版本正確的語法使用近「當‘批准’WHERE posts.status =手動? GROUP BY posts.title令」 – 2009-09-08 17:41:20

+0

你能解釋一下你實際上是試圖在你的問題來實現的,好嗎?用簡單的英語。例如,「我試圖獲得5個帖子最意見,其狀態爲‘已批准’」除與標記的一部分。 – 2009-09-08 17:47:45

+0

除COUNT(*)外,此代碼正常工作。謝謝您的幫助! – 2009-09-08 17:54:03

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 
+0

此代碼給了我這個錯誤: 「你在你的SQL語法錯誤;檢查對應於你的MySQL服務器版本使用附近的正確語法手冊「AS commentsCount),1,0)FROM帖子INNER JOIN ON comments.postID = P意見」 – 2009-09-08 17:27:59

+0

@Arms,我編輯的IF語句平衡括號。 – dnagirl 2009-09-08 17:45:33

+0

現在這個工作,謝謝:) 我很好奇,如果你的方法比我發佈的自己的答案更有效或更低效。 – 2009-09-08 17:52:38

0

基於關閉喬希·戴維斯的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