小编典典

SQL更新-多列

sql

我想基于第二个表中Select的值使用一条语句来更新表中的多个列,以获取如下所示的值:

UPDATE tbl1 
SET (col1, col2, col3) = (SELECT colA, colB, colC 
                          FROM tbl2 
                          WHERE tbl2.id = 'someid') 
WHERE tbl1.id = 'differentid'

但是,似乎不可能“设置”一个以上的列名-是否有替代方法,而不是为每个列编写单独的更新语句?

UPDATE tbl1 
SET col1 = (SELECT colA FROM tbl2 WHERE tbl2.id = 'someid') 
WHERE tbl1.id = 'differentid'

UPDATE tbl1 
SET col2 = (SELECT colB FROM tbl2 WHERE tbl2.id = 'someid') 
WHERE tbl1.id = 'differentid'

UPDATE tbl1 
SET col3 = (SELECT colC FROM tbl2 WHERE tbl2.id = 'someid') 
WHERE tbl1.id = 'differentid'

阅读 356

收藏
2021-04-22

共1个答案

小编典典

update tbl1
set col1 = a.col1, col2 = a.col2, col3 = a.col3
from tbl2 a
where tbl1.Id = 'someid'
and a.Id = 'differentid'
2021-04-22