簡體   English   中英

連接表上的 SQL 更新查詢

[英]SQL update query on join table

UPDATE 
    t1
SET 
    t1.c3 = t2.c3,
    t1.c4 = t1.c4 
FROM 
    t1
    LEFT JOIN t2 ON t1.c1 = t2.c1 AND t1.c2 = t2.c2
WHERE 
    t1.c5 = 'In Progrss'

我想從表 t2 的頂行更新值。

例如,在 t2 表中,有 3 行且條件匹配僅高於update in t1 table(ROW ID 3 VALUES TO UPDATE IN t1 table)頂行值update in t1 table(ROW ID 3 VALUES TO UPDATE IN t1 table)

t2表:

id  c1      c2     c3     c4
-----------------------------
1   ABC     XYZ    280    300
2   ABC     XYZ    290    400
3   ABC     XYZ    310    500
4   PQR     STR    210    400

t1表:

id  c1      c2     c3     c4   c5
----------------------------------
1   ABC     XYZ                In Progrss
5   ABC     XYZ                In Progrss
8   ABC     XYZ                In Progrss
15  PQR     STR                IN Progress

Postgres 的更新/連接語法如下:

update t1
set c3 = t2.c3, c4 = t1.c4
from t2
where 
    t1.c1 = t2.c1 
    and t1.c2 = t2.c2
    and t1.c5 = 'In Progress'

如果t2有多個匹配的行並且您想要具有最小id ,那么您可以在子查詢中使用row_number()

update t1
set c3 = t2.c3, c4 = t1.c4
from (select t2.*, row_number() over(partition by c1, c2 order by id) rn from t2) t2
where 
    t1.c1 = t2.c1 
    and t1.c2 = t2.c2
    and t1.c5 = 'In Progress'
    and t2.rn = 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM