如果没有其他共同点,如何从多个其他表中更新表1?

时间:2019-10-02 18:54:05

标签: sql sql-server sql-server-2017

我有一个主表和其他3个表。这些表中的每个表仅具有一行。我想用其他表中的相应列更新TableMain的列。这些表没有我可以加入的任何列。

create table TableMain(a1 int, a2 int, b1 int, b2 int, c1 int, c2 int)
create table TableA(a1 int, a2 int)
create table TableB(b1 int, b2 int)
create table TableC(c1 int, c2 int)

我有以下方法可行,但看上去很可怕:

update TableMain
set a1 = (select a1 from TableA),
    a2 = (select a2 from TableA),
    b1 = (select b1 from TableB),
    b2 = (select b2 from TableB),
    c1 = (select c1 from TableC),
    c2 = (select c2 from TableC)

我已经尝试了下面的代码,但是我得到了NULL,所以这种方法行不通:

update TableMain
set a1 = ta.a1, a2 = ta.a2, 
    b1 = tb.b1, b2 = tb.b2, 
    c1 = tc.c1, c2 = tc.c2, 
from TableA ta, TableB tb, TableC tc

是否有更优雅的方式来更新这些列?

P.S。我问过类似的question,但它解决了从单个表进行更新的问题。

1 个答案:

答案 0 :(得分:1)

考虑:

UPDATE tm
SET tm.a1 = ta.a1,
    tm.a2 = ta.a2, 
    tm.b1 = tb.b1, 
    tm.b2 = tb.b2, 
    tm.c1 = tc.c1, 
    tm.c2 = tc.c2
FROM TableMain tm
CROSS JOIN TableA ta
CROSS JOIN TableB tb
CROSS JOIN TableC tc