gpt4 book ai didi

sql - 使用选择多个表 postgres 更新行

转载 作者:行者123 更新时间:2023-11-29 13:43:48 25 4
gpt4 key购买 nike

我有这些表和值:

Table1                 Table2                
------------------ --------
ID | CREATED_BY ID | NAME
------------------ --------
1 | 1 | aaa
2 | 2 | bbb
3 | 3 | ccc
4 | 4 | ddd


Table1_2_link
--------------------------
ID | TABLE1_ID | TABLE2_ID
--------------------------
1 | 1 | 1
2 | 2 | 2
3 | 3 | 3
4 | 3 | 4

我想用表 2 中的名称值更新表 1 中的 created_by 列,其中表 1_2_link 只有一对(TABLE1_ID、TABLE2_ID)。

更新后的结果必须是:

Table1             
------------------
ID | CREATED_BY
------------------
1 | aaa
2 | bbb
3 |
4 |

有没有办法用简单的 SQL 查询来做到这一点?

最佳答案

您需要一个join update:

update table1 t1
set created_by = t2.name
from (select t12.TABLE1_ID, max(t12.TABLE2_ID) as TABLE2_ID
from Table1_2_link t12
group by t12.TABLE1_ID
having count(*) = 1
) t12 join
table2 t2
on t12.TABLE2_ID = t2.id
where t12.TABLE1_ID = t1.id;

Table1_2_link 上的子查询查找只有一行的 ID。当只有一行时,MAX() 返回该行中 TABLE2_ID 的值。

关于sql - 使用选择多个表 postgres 更新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51651173/

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