这篇文章主要讲解了“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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。