MySql if Then in Select Statement

I want to use the IF THEN statement in mysql selection, but can't figure it out. When there are no comments yet, the value created by the comment must be the created value of the element itself. This is the request:

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

I would think about this, but it does not work:

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

What is the best way to do this?

+3
source share
3 answers

Can be used IFNULL

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

OR IF

IF(max(comments.created)='NULL', max(comments.created), item.created) 
AS commentcreated
+10
source
coalesce(max(comments.created), item.created) as commentcreated 
+4
source

IF... THEN... ELSE , , - , IFNULL Coalesce ajreal Redfilter .

... ... ELSE SQL, , . .

0
source

Source: https://habr.com/ru/post/1780956/


All Articles