我如何在PostgresQL中做类似的事情?

时间:2019-10-25 02:12:49

标签: postgresql

这是我想发生的片段。这可能吗?

INSERT INTO join_table_1(table_1_id,table_2_id)
SELECT id, (INSERT INTO table_2(id) VALUES (uuid_generate_v4()) RETURNING id) 
FROM table_1

也正在查看TRIGGER,但我找不到返回新插入行的ID的方法

1 个答案:

答案 0 :(得分:1)

对我来说,要实现的目标还不是很清楚,但我认为您正在寻找的是data modifying CTE

with new_t2 as (
  INSERT INTO table_2(id) 
  VALUES (uuid_generate_v4()) 
  RETURNING id
) 
INSERT INTO join_table_1 (table_1_id, table_2_id)
SELECT id, (select id from new_t2) 
FROM table_1