您好,登錄后才能下訂單哦!
這篇文章主要講解了“PostgreSQL數據庫中如何從update返回old”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“PostgreSQL數據庫中如何從update返回old”吧!
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 least id 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.留著做參考吧 .
感謝各位的閱讀,以上就是“PostgreSQL數據庫中如何從update返回old”的內容了,經過本文的學習后,相信大家對PostgreSQL數據庫中如何從update返回old這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。