表格1:
BrID HQID
------------
Br1 HQ1
HQ1
HQ2
Br2 HQ1
Br3 HQ2
表2:
ID Name BrID IDt2
------------------------------
11 OthName11 Br1
22 HQName111 HQ1
33 HQName222 HQ2
44 OthName22 Br2
55 OthName33 Br3
我需要更新Table1中具有HQID值但Table2.ID由Table1.HQID = Table2.BrID连接的每一行的Table2.IDt2
换句话说,是第一行。
SELECT HQID FROM Table1 WHERE BrID = 'Br1'
SELECT ID WHERE Table2.BrID = HQID (from previous SELECT)
UPDATE Table2 SET IDt2 = ID(from previous SELECT) WHERE Table2.BrID = 'Br1' (from first SELECT)
结果应该是Table2:
ID Name BrID IDt2
------------------------------
11 OthName11 Br1 22
22 HQName111 HQ1
33 HQName222 HQ2
44 OthName22 Br2 22
55 OthName33 Br3 33
是否可以在一次UPDATE中完成?
我还能怎么做?
最佳答案
您只需要多个JOIN
语句:
UPDATE a
SET a.IDT2 = c.ID
FROM Table2 a
JOIN Table1 b
ON a.BRID = b.BRID
JOIN TAble2 c
ON b.HQID = c.BRID
演示:SQL Fiddle