gpt4 book ai didi

sql - 如何在没有公共(public)键的情况下从另一个表更新一个表中的列

转载 作者:行者123 更新时间:2023-11-29 12:49:45 25 4
gpt4 key购买 nike

这可能是非常基本的,但我不知道要搜索什么。

表 1:

someid value
1 0
2 0
3 0

表 2:

someid value
9 1
10 2
11 3

我想用 Table2.value 逐行更新 Table1.value 值,没有公共(public)键,没有 where 子句只是 table1.value row1 = table2 .value row1 等。就像水平联合。

所以 Table1 应该是:

someid value
1 1
2 2
3 3

我尝试:

update table1
set value = table2.value
from table2

但所有值都来自表 2 的第一行:

1   1
2 1
3 1

最佳答案

您可以使用row_number():

update table1 
set value = t2.value
from (
select id, value, row_number() OVER (ORDER BY id) AS n from table1
) t inner join (
select id, value, row_number() OVER (ORDER BY id) AS n from table2
) t2 on t.n = t2.n
where t.id = table1.id

参见 demo .
表 1 的结果:

> id | value
> -: | ----:
> 1 | 1
> 2 | 2
> 3 | 3

如果确定table1中的id是从1开始连续无间隙的,那么查询可以这样简化:

update table1 
set value = t2.value
from (
select id, value, row_number() OVER (ORDER BY id) AS n from table2
) t2
where t2.n = table1.id

参见 demo .

关于sql - 如何在没有公共(public)键的情况下从另一个表更新一个表中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57061530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com