MySQL 如果不为空,则选择列值,否则使用另一个列值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3952406/
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 17:28:23  来源:igfitidea点击:

Select column value if not null else use another column value

mysql

提问by Jerry2

I have 2 columns in mysql table: a and b. a is allways string value and b is sometimes a string value and sometimes it is null.

我在 mysql 表中有 2 列:a 和 b。a 始终是字符串值,b 有时是字符串值,有时为空。

How to construct a mysql SELECT so that the b would be taken if it is not null and a would be taken otherwise.

如何构造一个 mysql SELECT 以便如果 b 不为空则采用 b 否则采用 a 。

I tried to make some magic with concat and if...then with no success...

我试图用 concat 创造一些魔法,如果……那么没有成功……

UPDATE - To extend my question, is there a function that would work like Ifnull but would work for null AND empty values?

更新 - 为了扩展我的问题,是否有一个函数可以像 Ifnull 一样工作但可以用于 null 和空值?

回答by Mark Byers

Use IFNULL(b, a).

使用IFNULL(b, a)

If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2.

如果 expr1 不为 NULL,则 IFNULL() 返回 expr1;否则返回 expr2。

This is a MySQL specific function. You can also use COALESCEin the same way. This will work in more databases but it has slightly worse performance in MySQL than IFNULL.

这是 MySQL 特定的功能。您也可以以相同的方式使用COALESCE。这将适用于更多数据库,但它在 MySQL 中的性能比 IFNULL 稍差。

回答by Amber

回答by Eyal Ch

IF(expr1,expr2,expr3)

If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL) then IF() returns expr2; otherwise it returns expr3.

如果 expr1 为 TRUE(expr1 <> 0 和 expr1 <> NULL),则 IF() 返回 expr2;否则返回 expr3。