Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3056345
  • 博文数量: 206
  • 博客积分: 3409
  • 博客等级: 中校
  • 技术积分: 4066
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-24 10:21
个人简介

● ITPUB名人堂嘉宾 ● ChinaUnix社区博客专家 ● ChinaUnix社区Oracle板块版主 ● 优酷网认证音乐牛人:EricGuitar ● SDOUG 核心成员 ●E-mail:gaoqiangdba@163.com

文章分类

全部博文(206)

文章存档

2021年(11)

2020年(7)

2019年(7)

2016年(5)

2015年(36)

2014年(23)

2013年(15)

2012年(23)

2011年(61)

2010年(18)

分类: Mysql/postgreSQL

2016-03-19 16:04:24


在数字加减乘除运算中遇到某个字段值为空值(null)的时候,输出的结果往往会让我们失望,得不到我们所期待的数值,可以通过 coalesce方式将凡是取值为null,即空值的字段转换成默认的值进行运算,从而改善运算效果。


 coalesce函数用法:
 coalesce(字段名,默认值),很简单吧~


演示如下:
[root@dbserver ~]# su - postgres
-bash-3.2$ psql music
psql (9.5beta2)
输入 "help" 来获取帮助信息.
music=# create table test_null(id int,num1 int,num2 int);
CREATE TABLE


插入数据,有的取值为正常数字,有的则为空值null:
music=# insert into test_null values(1,100,100);
INSERT 0 1
music=# insert into test_null values(2,200,200);
INSERT 0 1
music=# insert into test_null values(3,null,100);
INSERT 0 1
music=# insert into test_null values(4,300,null);
INSERT 0 1
music=# insert into test_null values(5,null,500);
INSERT 0 1


查看一下表中的数据,发现null值的字段全部为空值:
music=# select * from test_null; 
 id | num1 | num2 
----+------+------
  1 |  100 |  100
  2 |  200 |  200
  3 |      |  100
  4 |  300 |     
  5 |      |  500
(5 行记录)




直接运算查看结果,会发现凡是遇到空值的运算结果均为空:
music=#  select num1+num2 from test_null;
 ?column? 
----------
      200
      400
         
         
         
(5 行记录)




使用 coalesce函数之后便可处理null的问题:
music=# select coalesce(num1,0)+coalesce(num2,0) from test_null;
 ?column? 
----------
      200
      400
      100
      300
      500
(5 行记录)


  在这里,coalesce设置的默认值为0,同样也可以设置为其他的数值,比如人体体温可以设置默认值为36,冰点为0,沸点为100等。
阅读(47631) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~