mysql IFNULL ELSE
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3215454/
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
mysql IFNULL ELSE
提问by mcgrailm
I have a select statement where I want to make select conditional like this
我有一个 select 语句,我想像这样使 select 有条件
IFNULL(field_a,field_a,feild_b)
so that it checks field a if a is null then the select would be field b
以便它检查字段 a 如果 a 为空,则选择将是字段 b
is that possible ?
那可能吗 ?
回答by OMG Ponies
Use COALESCE:
使用合并:
SELECT COALESCE(field_a, field_b)
COALESCE is an ANSI standard function that returns the first non-null value from the list of columns specified, processing the columns from left to right. So in the example, if field_a
is null, field_b
value will be displayed. However, this function will return NULL if there is no non-null value from the columns specified.
COALESCE 是一个 ANSI 标准函数,它返回指定列列表中的第一个非空值,从左到右处理列。所以在示例中,如果field_a
为空,field_b
则将显示值。但是,如果指定的列中没有非空值,则此函数将返回 NULL。
It's supported on MySQL (I've used it on 4.1), SQL Server (since v2000), Oracle 9i+...
它支持 MySQL(我在 4.1 上使用过)、SQL Server(自 v2000 起)、Oracle 9i+...
回答by user3590489
and another way to skin that cat (flexible for not just null comparisons)...
以及另一种给那只猫剥皮的方法(不仅适用于空比较灵活)...
select if(field_a is not null, field_a, field_b) from...
回答by Matt
回答by Developer
MySQL IFNULL() With Syntax & Examples
MySQL IFNULL() 带语法和示例
Syntax
句法
The syntax of the IFNULL function is:
IFNULL 函数的语法是:
IFNULL(expression_1,expression_2);
SELECT
name, IFNULL(businessphone, homephone) phone
FROM
users;
#The above query return this result from users table
+------------+-----------+----------+-----------
| id | name | phone |
+------------+-----------+----------+-----------
| 5 | Tommy Hill | (541) 754-3009 |
| 6 | John Smith | (541) 754-3110 |
| 10 | Mark Greenspan | (541) 754-3111 |
| 11 | Kelvin Row | (541) 754-3111 |
+------------+-----------+----------+-----------