我有包含许多现有行的表 x
x ( id, name)
我有一个新表 y,它目前是空的,(所有字段都有默认值)
y ( id, uuid )
我用新列 y_id 更新了 x
x ( id, name, y_id )
我想为 x 中的每一行填充 y,然后通过 y.id 将 x 与 y 相关联
这和我得到的一样接近,但这会将 x 的所有行设置为具有相同的 y.id。
with ys as (
insert into y(uuid) values(default)
returning id
)
update x set y_id = ys.id
from ys
您想为“x”的每个值填充“y”。但是你没有办法连接表格。但 。. .
with ys as (
insert into y
select -- this is empty on purpose to put in only default values
from x;
returning id
)
update x
set y_id = yy.id
from (select x.*, row_number() over (order by x_id) as seqnum
from x
) xx join
(select ys.*, row_number() over (order by y_id) as seqnum
from ys
) yy
on xx.seqnum = yy.seqnum
where x.x_id = xx.x_id;
这有什么作用?CTEy
为 中的每一行插入一行,并使用默认值x
。在insert
随后增加了序列号到X和Y的,使他们能够对齐,一个排一排。然后将该值用于更新。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句