在 postgres 中,我想将多行插入到第一个表中,然后使用生成的标识将多行插入到第二个表中。有没有办法将返回的 ID 与我的数据结合起来?
我有以下代码片段,其中我首先将新股息插入插入表中,然后使用这些生成的 ID 插入股息表中。
WITH inserted AS (
INSERT INTO transaction (transaction_id, transaction_date, mutation)
SELECT transaction_id, transaction_date, mutation FROM new_dividends
RETURNING transaction_id
)
INSERT INTO dividend (transaction_id, effect)
SELECT transaction_id, effect FROM inserted;
这不起作用,因为在第二次插入中,效果应该从 new_dividends 中选择,因为它不存在于返回语句中。
您从 CTE 中进行选择的事实并不会阻止您使用任何您想要的 join:demo:
WITH inserted AS (
INSERT INTO transaction (transaction_id, transaction_date, mutation)
SELECT transaction_id, transaction_date, mutation FROM new_dividends
RETURNING transaction_id
)
INSERT INTO dividend (transaction_id, effect)
SELECT transaction_id, effect FROM inserted NATURAL JOIN new_dividends;
table "transaction";
交易ID | 交易日期 | 突变 |
---|---|---|
1fdf6681-bac1-48c6-8a01-a80e742acb8a | 2023-10-31 10:39:29.333697+00 | 突变1 |
table new_dividends;
交易ID | 交易日期 | 突变 | 效果 |
---|---|---|---|
1fdf6681-bac1-48c6-8a01-a80e742acb8a | 2023-10-31 10:39:29.333697+00 | 突变1 | 效果1 |
table dividend;
交易ID | 效果 |
---|---|
1fdf6681-bac1-48c6-8a01-a80e742acb8a | 效果1 |