[英]postgresql: copy table1 to table2 and table3, but use returned table2 values to insert into table3
I have three tables: 我有三个表:
table1(id, name, foo)
table1(id,name,foo)
table2(id, name)table2(编号,名称)
table3(id, id2, name, foo, bar)table3(id,id2,name,foo,bar)
And I'd like to copy data from table1 to tables 2 & 3, but table3.id2 has to correspond to the row in table2. 我想将数据从表1复制到表2和3,但是table3.id2必须与table2中的行相对应。 I think I need to do something with the RETURNING command, but I have been unsuccessful.
我想我需要用RETURNING命令做些事情,但是我一直没有成功。
WITH oldstuff AS (
SELECT name, foo, 'some value' AS bar
FROM table1
),
newstuff AS (
INSERT INTO table2 (name)
SELECT name FROM oldstuff
RETURNING id AS id2 /* but i also need oldstuff.name, oldstuff.foo,and oldstuff.bar */
)
INSERT INTO table3 (id2, name, foo, bar)
SELECT * FROM newstuff; /* I cant just do a join here because the fields arent unique */
Conceptually, you would do: 从概念上讲,您将执行以下操作:
WITH oldstuff AS (
SELECT name, foo, 'some value' AS bar
FROM table1
),
newstuff AS (
INSERT INTO table2 (name)
SELECT name
FROM oldstuff
RETURNING *
)
INSERT INTO table3 (id2, name, foo, bar)
SELECT ns.id, ns.name, os.foo, os.bar
FROM newstuff ns join
oldstuff os
on ns.name = os.name;
From what you say, this doesn't do exactly what you want because there is not a unique name in newstuff
. 用您的话说,这并不能完全满足您的要求,因为
newstuff
没有唯一的名称。 Either generate a unique id for the original table or only insert unique data into it: 为原始表生成唯一的ID或仅向其中插入唯一的数据:
INSERT INTO table2 (name)
SELECT DISTINCT name
FROM oldstuff
RETURNING *;
Hmmm . 嗯。 .
。 .
。 There might be a kludgy way:
可能有一种怪诞的方式:
WITH oldstuff AS (
SELECT name, foo, 'some value' AS bar
FROM table1
),
newstuff AS (
INSERT INTO table2 (name)
SELECT name
FROM oldstuff
RETURNING *
)
INSERT INTO table3 (id2, name, foo, bar)
SELECT ns.id, ns.name, os.foo, os.bar
FROM (SELECT ns.*, ROW_NUMBER() OVER (PARTITION BY name ORDER BY name) as seqnum
FROM newstuff ns
) ns JOIN
(SELECT os.*, ROW_NUMBER() OVER (PARTITION BY name ORDER BY name) as seqnum
FROM oldstuff os
) os
on ns.name = os.name and ns.seqnum = os.seqnum;
This will work with duplicate names, and you get exactly one match in the final table. 这将使用重复的名称,并且在决赛桌中您将获得一个完全匹配的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.