nullif(var1,var2)
如果var1和var2相等则返回null,如果不相等则返回var1
select nullif(1,null); 结果:1
select nullif(null,1); 结果:null
select nullif(1,1); 结果:null
select nullif(1,0); 结果:1
create table posts(
id serial primary key,
title varchar(255) not null,
excerpt varchar(255),
body text,
create_tiem timestamp default current_timestamp,
update_time timestamp
);
insert into posts(title,excerpt,body) values
('test post 1','test post excerpt 1','test post body 1'),
('test post 2','','test post body 2'),
('test post 3', null ,'test post body 3');
案例1:
select id,title ,excerpt from posts;
结果:由结果得知excerpt有空值null
id title excerpt
1 test post 1 test post excerpt 1
2 test post 2
3 test post 3 [null]
案例2:
select id,title,coalesce(
excerpt,
left(body,40)
)
from posts;
结果:由结果得知null值的会做处理,但是对于''是不做处理的
id title excerpt
1 test post 1 test post excerpt 1
2 test post 2
3 test post 3 test post body 3
案例3:
select id,title,coalesce(
nullif(excerpt,''),
left(body,40)
)
from posts;
结果:由结果得知null值和''的都会做处理,因为使用了nullif函数
id title excerpt
1 test post 1 test post excerpt 1
2 test post 2 test post body 2
3 test post 3 test post body 3
left函数:
返回最左面 n 字符
select left('abcdefgh', 5); 结果:abcde
right函数:
返回最右面 n 个字符
select right('abcdefgh', 3); 结果:fgh
rpad函数:
字符不满 10 个,用 # 补满
select rpad('abcd', 10, '#'); 结果:abcd######
备注:COALESCE(currentcount,0)
如果currentcount不为null,返回currentcount。否则返回0。
PostgreSQL对空值处理nullif函数
最新推荐文章于 2024-07-18 16:32:46 发布