SELECT one column if the other is null

后端 未结 4 1887
星月不相逢
星月不相逢 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.

    0 讨论(0)
  • 2020-12-29 18:48

    Check out the COALESCE function.

    Takes a variable number of arguments and returns the first non-null one. It works fine with joins.

    0 讨论(0)
  • 2020-12-29 18:51
    SELECT COALESCE(a2.date, a1.date) ...
    
    0 讨论(0)
  • 2020-12-29 18:57

    Use a CASE statement for the select.

    SELECT CASE WHEN a2.date IS NULL THEN a1.date
        ELSE a2.date END AS mydate
    
    0 讨论(0)
提交回复
热议问题