sql - 如何在postgresql的另一个表中提取非唯一列
问题描述
我有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
基于这个讨论
,但我不能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
和其他脚本,只有移动数据的问题
解决方案
没有重复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;
推荐阅读
- c - 如何从C中的函数返回字符数组
- r - 如何在数据框中进行一次模糊匹配和一次精确匹配?
- mysql - SQL:按组排名,无需汇总或加入
- python - 如何根据数据点排列直线
- java - 为什么从子类调用超类方法时我的值为 null?
- python - 将 PySpark 数据框的列与标量相乘
- reactjs - 为除一条特定路线之外的所有路线渲染组件
- ios - 强制子视图控制器调用基本视图控制器方法
- sql-server - "Subquery returned more than 1 value" when combining tables with subquery
- javascript - 进行文本过渡,下方的文本移动以为上方的文本腾出空间