我在表
source
中有一个(大)数据集,我想转换该数据并将结果放入两个单独的表中,table_1
和table_2
,其中table_2
引用table_1
。我正在寻找一种不依赖于任何空表的解决方案,因此我无法以某种方式确定性地选择我的主键。
据我所知:
-- Example data. This will actually be a complex query.
create temporary table source
as select * from (values ('hello', 'world'), ('foo', 'bar')) as t(data_1, data_2);
-- Tables into which to insert the data.
create temporary table table_1(id serial primary key, data text);
create temporary table table_2(id serial primary key, table_1_id int references table_1, data text);
with
inserted_rows as (
insert into table_1(data)
select source.data_1
from source
returning id as table_1_id, source.data_2 as data_2)
insert into table_2(table_1_id, data)
select table_1_id, data_2
from inserted_rows;
如果我运行它,我会收到以下错误:
psql:captain/panel/migrations/0239_daily_billing_step_1_test.sql:17: ERROR: missing FROM-clause entry for table "source"
LINE 6: returning id as table_1_id, source.data_2 as data_2)
我明白它在说什么,但这似乎使得无法同时访问 CTE 中
insert
的生成主键以及 source
的列。