如何嵌套`insert ... returns`?

cev*_*ing 2 postgresql sql-insert

Postgresql可以返回自动递增的值returning:

insert into table1 (id) values (null) returning id;
Run Code Online (Sandbox Code Playgroud)

我试图将返回的值插入另一个表:

insert into table2 (id) values ((insert into table1 (id) values (null) returning id)) returning id;
Run Code Online (Sandbox Code Playgroud)

但是这会into在嵌套之前抛出语法错误insert.

如何使用内部的返回值insert作为外部的值insert

a_h*_*ame 5

您可以链接数据修改CTE:

with new_t1 as (
  insert into table1 (id) values (default) 
  returning id
)
insert into table2 (id) 
select id 
from new_t1;
Run Code Online (Sandbox Code Playgroud)

请注意,当您明确要求插入该列时,insert into table1 (id) values (null) returning id将返回.nullNULL

要确保生成值,您需要告诉Postgres使用该列的默认值,而不是NULL值.