SELECT one column if the other is null

后端 未结 4 1923
星月不相逢
星月不相逢 2020-12-29 18:03

I want to select a2.date if it\'s there, but if it\'s NULL I want to select a1.date (a2 is being left-joined). This:

4条回答
  •  清酒与你
    2020-12-29 18:38

    The ANSI means is to use COALESCE:

    SELECT COALESCE(a2.date, a1.date) AS `date`
       ...
    

    The MySQL native syntax is IFNULL:

    SELECT IFNULL(a2.date, a1.date) AS `date`
       ...
    

    Unlike COALESCE, IFNULL is not portable to other databases.

    Another ANSI syntax, the CASE expression, is an option:

    SELECT CASE
             WHEN a2.date IS NULL THEN a1.date
             ELSE a2.date
           END AS `date`
       ...
    

    It requires more direction to work properly, but is more flexible if requirements change.

提交回复
热议问题