PG 中返回update 前的值 :old
pg 資料庫中,如何從update 返回 :old .
pg 的update 語法裡有returning 字句 .
但是是返回的 修改的值, 相當於 ,
update 後 接著執行了 同樣條件的select 語法.
那麼如何返回 修改前的值呢 ?
UPDATE tbl xSET tbl_id = 23 , name = 'New Guy'FROM tbl y -- using the FROM clauseWHERE x.tbl_id = y.tbl_id -- must be UNIQUE NOT NULLAND x.tbl_id = 3RETURNING y.tbl_id AS old_id, y.name AS old_name , x.tbl_id , x.name;
old_id | old_name | tbl_id | name--------+----------+--------+--------- 3 | Old Guy | 23 | New Guy
WITH sel AS (
SELECT tbl_id, name FROM tbl WHERE tbl_id = 3 -- assuming unique tbl_id ), upd AS ( UPDATE tbl SET name = 'New Guy' WHERE tbl_id = 3 RETURNING tbl_id, name )SELECT s.tbl_id AS old_id, s.name As old_name , u.tbl_id, u.nameFROM sel s, upd u;
UPDATE tbl xSET tbl_id = 24
, name = 'New Gal'FROM (SELECT tbl_id, name FROM tbl WHERE tbl_id = 4 FOR UPDATE) y
WHERE x.tbl_id = y.tbl_id
RETURNING y.tbl_id AS old_id, y.name AS old_name, x.tbl_id, x.name;
對於 insert 怎麼辦呢 ?
WITH sel AS ( SELECT id, title FROM posts WHERE id IN (1,2) -- select rows to copy ), ins AS ( INSERT INTO posts (title) SELECT title FROM sel RETURNING id, title )SELECT ins.id, sel.id AS from_idFROM insJOIN sel USING (title);
If
title
is not unique per query (but at leastid
is unique per table):WITH sel AS ( SELECT id, title, row_number() OVER (ORDER BY id) AS rn FROM posts WHERE id IN (1,2) -- select rows to copy ORDER BY id ), ins AS ( INSERT INTO posts (title) SELECT title FROM sel ORDER BY id -- ORDER redundant to be sure RETURNING id )SELECT i.id, s.id AS from_idFROM (SELECT id, row_number() OVER (ORDER BY id) AS rn FROM ins) iJOIN sel s USING (rn);This second query relies on the undocumented implementation detail that rows are inserted in the order provided. It works in all current versions of Postgres and is probably not going to break.
留著做參考吧 .
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/133735/viewspace-2662887/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- springMVC中controller的返回值SpringMVCController
- 多型中的返回值型別多型型別
- Go中多個返回值的技巧Go
- Oracle中的for update 和 for update nowaitOracleAI
- js中的typeof返回值的所有型別JS型別
- 觸發器 REFERENCING OLD AS OLD觸發器
- vue 中this.$emit()的返回值是什麼?VueMIT
- 函式的返回值函式
- CQRS中命令可以返回值嗎? -OSKAR
- Python的and和or的返回值Python
- typeof返回值
- Laravel 返回值Laravel
- MybatisPlus中的update操作MyBatis
- Python中獲取執行緒返回值的常用方法!Python執行緒
- 如何在Typescript中定義Promise的返回值型別TypeScriptPromise型別
- [轉載] Java中如何在方法中return返回多個值Java
- Java中形式引數與返回值問題Java
- 理解String的compareTo()方法返回值
- 演算法題:返回滑動視窗中的最大值演算法
- Python中定義(建立)、呼叫函式及返回值Python函式
- 線上直播原始碼,fragment中onActivityForResult得到返回值原始碼Fragment
- 使用javaURL從介面頁面中獲得返回值Java
- typeof返回值詳解
- 0305函式返回值函式
- cin和scanf的返回值知多少
- C語言中函式的返回值C語言函式
- select @@Identity 返回自增主鍵的值IDE
- windows.old可以刪除嗎?windows.old檔案的刪除方法Windows
- 檢視當前pg會話連線數會話
- python 呼叫 shell ,獲取返回值和返回資訊Python
- Solidity中函式返回值,靜態動態陣列Solid函式陣列
- PG中級證書到手,PostgreSQL(PG)認證SQL
- c語言中返回整數值的長度C語言
- 【轉】[C#] 建立返回多個值的方法C#
- require的到底有沒有返回值?UI
- Python的函式能返回多個值嗎Python函式
- VS 返回值被忽略的解決方法
- Laravel response 返回的值全部處理為字串Laravel字串