ifnull
如果第一个参数不为空,则返回第一个参数,否则返回第二个参数。
此函数是 coalesce() 的替代方案。如果 x 不为 null,则返回 x;否则返回 y。参数可以是常量值、数组、序列、时间或上述任何类型的表列。当需要结果但不确定字段值是否存在时,这可能会很有用。
ifnull( x, y );
参数
x
要测试是否为空的参数;如果 x 不为空则返回此参数。
y
如果 x 为空则返回的值。
示例
示例1
ifnull() 函数可以与如下简单的参数一起使用:
select ifnull( 1, 2), ifnull( null, 2);
#1 #2
--------------------------------------------------------
1 2
示例2
或者它可以用于不同类型的表列。例如,考虑下面的表 t,用以下两行值进行初始化:
create table t(
i1 int, i2 int,
ch1 char(20), ch2 char(20),
sc1 sequence(char(5)), sc2 sequence(char(5)),
si1 sequence(int), si2 sequence(int),
a1 array(int), a2 array(int),
t1 time, t2 time,
d1 decimal(15,2), d2 decimal(15,2),
b1 boolean, b2 boolean
);
insert into t values(null, 1,
null, 'ch1',
null, ['1','2','3','4','5'],
null, [1,2,3,4,5],
null, [1,2,3,4,5,6,7,8,9,0],
null, '04-02-2019 10:19',
null, 10.2,
null, true);
insert into t values(2, NULL,
'ch2', null,
['a1','a2','a3','a4','a5'], null,
[11,12,13,14,15], null,
[10,20,30,40,50], null,
'04-02-2019 10:23', null,
10.02, null,
null, false);
以下的 SELECT 语句使用了 ifnull() 函数从每个指定的字段中提取非空值(请注意,此处对 SELECT 结果进行了重新格式化,以便更易于看出它们与字段之间的对应关系):
select ifnull(i1, i2) as i,
ifnull(ch1, ch2) as ch,
ifnull(sc1, sc2) as sc,
ifnull(si1, si2) as si,
ifnull(a1, a2) as a,
ifnull(t1, t2) as t,
ifnull(d1, d2) as d,
ifnull(b1, b2) as b
from t order by i;
i
ch
sc
si
a
t
d
b
--------------------------------------------------------
1
ch1
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
04/02/2019 10:19:00
10.20
true
2
ch2
{a1, a2, a3, a4, a5}
{11, 12, 13, 14, 15}
[10, 20, 30, 40, 50]
04/02/2019 10:23:00
10.02
false