我们都知道在oracle数据库中有一个merge的功能,那就是实现在发现某条记录对应的关键字在数据表中存在时就根据关键字做更新数据操作,若在数据表中没有发现此关键字时,那么就直接做新增操作

postgresql 查询并设置新的列名(浅谈postgresql数据库中更新数据)(1)

SQL:

merge into bonuses d

using (select employee_id, salary, department_id from employees

where department_id = 80) s

on (d.employee_id = s.employee_id)

when matched thenupdateset d.bonus = d.bonus s.salary*.01

whennot matched theninsert (d.employee_id, d.bonus)

values (s.employee_id, s.salary*0.01);

在中国加上脱ioe的进程中,很多公司都在选择适合自己的数据库,所以开源的postgresql就进入了大家的视线

今天我们就来说说PG数据库的merge功能

如下:

1.创建一个简单的数据库表

postgresql 查询并设置新的列名(浅谈postgresql数据库中更新数据)(2)

2.执行类oracle的merge的pg数据库对应语句,出师不利,报错了

postgresql 查询并设置新的列名(浅谈postgresql数据库中更新数据)(3)

3.创建关键字

postgresql 查询并设置新的列名(浅谈postgresql数据库中更新数据)(4)

4.重新执行SQL语句

postgresql 查询并设置新的列名(浅谈postgresql数据库中更新数据)(5)

5.查询插入数据

postgresql 查询并设置新的列名(浅谈postgresql数据库中更新数据)(6)

6.再次执行修改语句

postgresql 查询并设置新的列名(浅谈postgresql数据库中更新数据)(7)

从上面步骤可以看出,在pg里面实现数据的如果存在则更新,不存在则插入需要注意

postgresql 查询并设置新的列名(浅谈postgresql数据库中更新数据)(8)

注意,使用 on confict,需要这个建立约束,否则错误如下

[Err] ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification

本文由美丽的程序猿原创并首发头条平台,转载请标明出处,欢迎关注美丽的程序猿头条号,还有更多程序猿可能碰到的各种技术小问题

,