我有sample_source
表,其中包含4列:
---------------------------------------------------
|id | name | target_value | another_target_value |
===================================================
|1 | John | 'wow' | 'value' |
---------------------------------------------------
|2 | Liza | 'wow' | 'value' |
---------------------------------------------------
|3 | Mark | 'awesome' | 'value' |
---------------------------------------------------
|4 |Daniel| 'awesome' | 'value' |
---------------------------------------------------
我想提取target_value
和another_target_value
到表values
(重复)
尝试写类似的东西
with cte as (insert into values(target_value, another_target_value)
select target_value, another_target_value from sample_source t1
returning id, t1.id as source_id)
update
sample_source
set
value_id = cte.id
where
sample_source.id = cte.source_id
基于this discussion
但我不能在返回子句中使用sample_source
表
UPD 预期结果:
sample_source
------------------------
|id | name | value_id |
========================
|1 | John | 1 |
------------------------
|2 | Liza | 2 |
------------------------
|3 | Mark | 3 |
------------------------
|4 |Daniel| 4 |
------------------------
values
--------------------------------------------
|id | target_value | another_target_value |
============================================
|1 | 'wow' | 'value' |
--------------------------------------------
|2 | 'wow' | 'value' |
--------------------------------------------
|3 | 'awesome' | 'value' |
--------------------------------------------
|4 | 'awesome' | 'value' |
--------------------------------------------
当然我有create
,alter
和其他脚本,仅在移动数据时出现问题
答案 0 :(得分:0)
在没有id
的情况下进行复制是很奇怪的。您可以在每个表中依次枚举 来完成所需的操作:
with i as (
insert into vals (target_value, another_target_value)
select target_value, another_target_value
from sample_source t1
returning id, t1.id as source_id
),
i2 as (
select i.*,
row_number() over (partition by target_value, another_target_value order by target_value) as seqnum
from i
)
update sample_source ss
set value_id = i2.id
from (select ss2.*,
row_number() over (partition by target_value, another_target_value order by target_value) as seqnum
from sample_source ss2
) ss2 join
i2
on i2.target_value = ss2.target_value and
i2.another_target_value = ss2.another_target_value and
i2.seqnum = ss2.seqnum
where ss.id = ss2.id;