PostgreSQL returning子句

在数据库中当我们update了一行记录后,如果我们将来想要查看当前记录更新前是哪条记录该怎么办呢?

pg中支持retuning子句,可以实现相应的功能。目前PostgreSQL支持insert,delete,update的returning。

insert returning 返回的是新插入的值。
delete returning 返回的是被删除的值。
update returning 返回的是更新后的值,不能返回更新前的值。

那么我们即使使用update returning的方式也只能返回update之后的值,对于我们前面提到到想要查看更新前的值要怎么做呢,我们可以通过其它方法实现。

例子:
update returning 返回的是更新后的值:

bill@bill=>create table test (old text, new text, mod_time timestamp);
CREATE TABLE
bill@bill=>insert into test values ('old', 'new', now());
INSERT 0 1
bill@bill=>select * from test ;
 old | new |         mod_time          
-----+-----+---------------------------
 old | new | 2020-03-05 14:11:01.54066
(1 row)
bill@bill=>update test set new='bill', old=new, mod_time=clock_timestamp() returning *;
 old | new  |          mod_time          
-----+------+----------------------------
 new | bill | 2020-03-05 14:11:18.058718
(1 row)

UPDATE 1

delete returning返回删除前的值:

bill@bill=>delete from test returning *;
 old | new  |          mod_time          
-----+------+----------------------------
 new | bill | 2020-03-05 14:11:18.058718
(1 row)

DELETE 1

returning 后的子句类似select … from 中的子句, 所以也支持表达式 :

bill@bill=>update test set new='bill', old=new, mod_time=clock_timestamp() returning 1,2,3,old,new,mod_time,old||new;
 ?column? | ?column? | ?column? | old | new  |          mod_time          | ?column? 
----------+----------+----------+-----+------+----------------------------+----------
        1 |        2 |        3 | new | bill | 2020-03-05 14:21:24.806337 | newbill
(1 row)

update returning返回旧值:
我们可以将更新的字段值赋值给其它字段,因为如果将一个字段的值赋予给另一个字段, 那会将更新前的值赋予给它, 而不是更新后的值。

bill@bill=>update test set new='bill', old=new, mod_time=clock_timestamp() returning 1,2,3,old,new,mod_time,old||new;
 ?column? | ?column? | ?column? | old | new  |          mod_time          | ?column? 
----------+----------+----------+-----+------+----------------------------+----------
        1 |        2 |        3 | new | bill | 2020-03-05 14:22:05.393243 | newbill
(1 row)

UPDATE 1
发布了116 篇原创文章 · 获赞 50 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_39540651/article/details/104700564