MySQL 如果另一列为空,则选择一列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5697942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 19:32:49  来源:igfitidea点击:

SELECT one column if the other is null

mysqlsql

提问by James

I want to select a2.dateif it's there, but if it's NULLI want to select a1.date(a2is being left-joined). This:

我想选择a2.date它是否在那里,但如果它在那里,NULL我想选择a1.datea2正在左连接)。这个:

SELECT a2.date OR a1.date
       ...

Simply returns a boolean result (as one would expect), how do I get the actual value of the non-null column though? (a2.dateis preferred, but if it's null then a1.date)

简单地返回一个布尔结果(正如人们所期望的那样),我如何获得非空列的实际值?(a2.date是首选,但如果它为空则a1.date)

回答by OMG Ponies

The ANSI means is to use COALESCE:

ANSI 的意思是使用COALESCE

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

The MySQL native syntax is IFNULL:

MySQL 原生语法是IFNULL

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

Unlike COALESCE, IFNULL is not portable to other databases.

与 COALESCE 不同,IFNULL 不可移植到其他数据库。

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

另一个 ANSI 语法,CASE 表达式,是一个选项:

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.

它需要更多的指导才能正常工作,但如果需求发生变化,则更加灵活。

回答by Rasika

Use a CASEstatementfor the select.

使用CASE语句进行选择。

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

回答by dkretz

Check out the COALESCE function.

查看 COALESCE 函数。

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

采用可变数量的参数并返回第一个非空参数。它适用于连接。

回答by pilcrow

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