这篇文章主要讲解了“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这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!