'returning'子句可以返回未插入的源列吗?


14

这是我的现实问题的一个最小示例:

create table t(id serial primary key, rnd double precision);

当然,您可以使用returning子句返回插入的列:

with w as (insert into t(rnd) values(random()) returning *)
insert into t(rnd) select random() from w returning *;
/*
| ID |            RND |
|----|----------------|
|  9 | 0.203221440315 |
*/

您还可以返回文字:

with w as (insert into t(rnd) values(random()) returning *)
insert into t(rnd) select random() from w returning *, 1.0 dummy;
/*
| ID |            RND | DUMMY |
|----|----------------|-------|
| 11 | 0.594980469905 |     1 |
*/

但您无法返回源列:

with w as (insert into t(rnd) values(random()) returning *)
insert into t(rnd) select random() from w returning *, w.rnd;
/*
ERROR: missing FROM-clause entry for table "w": with w as (insert into t(rnd) values(random()) returning *) insert into t(rnd) select random() from w returning *, w.rnd
*/

有什么办法可以使我w.rnd摆脱最终returning条款?

db <> 在这里拨弄


在MS SQL Server中,仅MERGE语句允许返回其他列。也许这也适用于postgres。
塞巴斯蒂安·梅恩

Answers:


12

RETURNING条款的文档说:

插入每行后,由INSERT命令计算并返回的表达式。该表达式可以使用由table_name命名的表的任何列名称。写入*返回插入行的所有列。

显然,这不适用于其他表中的列。

尽管我并没有真正理解问题的要点(即为什么要这么做-我想是因为它与原始版本有点太抽象了),但可能的解决方案可以是:

WITH w AS (INSERT INTO t(rnd) VALUES (random()) RETURNING *),
     x AS (INSERT INTO t(rnd) SELECT random() FROM w RETURNING *)
SELECT w.rnd, x.rnd
  FROM w, x;

也就是说,您可以在查询的开头放置多个可写CTE。请在dbfiddle上查看此操作。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.