2010-12-17 91 views
3

我想在mysql select中使用IF THEN語句,但無法弄清楚。當沒有評論時,評論創建的值應該是該項目本身的創建值。這是查詢:MySql如果然後在選擇語句

SELECT item.*, 
    count(comments.itemid) AS commentcount, 
    max(comments.created) AS commentcreated 
FROM table_items AS item 
LEFT JOIN table_comments AS comments ON (comments.itemid = item.id) 
WHERE item.published=1 
GROUP BY item.id 
ORDER BY item.created DESC 

我已經想通這一點,但它不工作:

... 
, IF max(comments.created)!='NULL' 
THEN max(comments.created) AS commentcreated 
ELSE item.created AS commentcreated 
END IF; 
FROM ....... 

什麼(最好)的方式來做到這一點?

回答

10

可以使用IFNULL

IFNULL(max(comments.created), item.created) AS commentcreated 

OR IF

IF(max(comments.created)='NULL', max(comments.created), item.created) 
AS commentcreated 
+0

哇,謝謝!奇蹟般有效! – Bert 2010-12-17 22:20:59

4
coalesce(max(comments.created), item.created) as commentcreated 
+0

也很好用!任何理由選擇這一個:IFNULL(max(comments.created),item.created)AS commentcreated? – Bert 2010-12-17 22:22:25

+0

我不知道MySQL有'IFNULL',那也沒關係。 'COALESCE'處理超過2個值,在這種情況下你不需要這些值。 – RedFilter 2010-12-17 22:48:33

0

您不能使用IF ... THEN ... ELSE建設內嵌在一個語句,如部分的表達式來產生單一值 - 這就是IFNULL和COALESCE函數的用途,就像ajreal和Redfilter所暗示的那樣。

IF ... THEN ... ELSE只適用於包含許多不同陳述的SQL代碼塊,例如在存儲過程中。