服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - PostgreSQL - PostgreSQL COALESCE使用方法代码解析

PostgreSQL COALESCE使用方法代码解析

2021-02-21 17:15手撕高达的村长 PostgreSQL

这篇文章主要介绍了PostgreSQL COALESCE使用方法代码解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

有这种要求,更新自己本身的字段的某个值进行加或者减

常规方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
UPDATE
  tbl_kintai_print_his
SET
  print_time = now(),
  print_emp_cd = '000000',
  times = (select times from tbl_kintai_print_his where  kokyaku_cd  = '000002' AND
  sagyo_ymd  = '2015-01-30'
+ 1,
  pattern = '055' ,
  ko_item_1 = 'no.0' ,
  ko_item_2 = 'no.2' ,
  ko_item_3 = 'no.3' ,
  ko_item_4 = 'no.4' ,
  ko_item_5 = 'no.5'
WHERE
  kokyaku_cd  = '000002' AND
  sagyo_ymd  = '2015-01-30'

能实现,不过效率肯定不高,要进行查询两次

pgsql里面提供一个函数能完成这个操作:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
UPDATE
  tbl_kintai_print_his
SET
  print_time = now(),
  print_emp_cd = '000000',
  times = COALESCE (SUM(times),0)+ 1,
  pattern = '055' ,
  ko_item_1 = 'no.0' ,
  ko_item_2 = 'no.2' ,
  ko_item_3 = 'no.3' ,
  ko_item_4 = 'no.4' ,
  ko_item_5 = 'no.5'
WHERE
  kokyaku_cd  = '000002' AND
  sagyo_ymd  = '2015-01-30'

能直接取到上一次的结果进行添加

二:还有一种用法就是在几个字段中取值,从前往后,一直取到不为NULL的值为止。

select id , name ,coalesce(Ph_no,Alt_no,Office_no) as contact number from employee

我们可以通过这样的语句,来得到Ph_no,Alt_no,Office_no这几个字段中,第一个不存在null的数值,上面的语句得到

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/sunxun/p/4260023.html

延伸 · 阅读

精彩推荐