我想在mysql select中使用IF THEN语句,但无法弄明白。当还没有评论时,评论创建的值应该是项目本身的创建值。这是查询:
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 .......
最好的方法是什么?
答案 0 :(得分:10)
可以使用IFNULL
IFNULL(max(comments.created), item.created) AS commentcreated
或IF
IF(max(comments.created)='NULL', max(comments.created), item.created)
AS commentcreated
答案 1 :(得分:4)
coalesce(max(comments.created), item.created) as commentcreated
答案 2 :(得分:0)
你不能在单个语句中使用IF ... THEN ... ELSE构造,作为表达式的一部分来产生单个值 - 这就是IFNULL和COALESCE函数的用途,如ajreal和Redfilter建议。
IF ...那么...... ELSE仅适用于包含许多不同语句的SQL代码块,例如:在存储过程中。