UPDATE和SELECT到/从同一个表

时间:2014-07-11 04:25:26

标签: sql sql-server select join sql-update

表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中的每一行更新Table2.IDt2,其中包含HQID值但Table2.ID由Table1.HQID = Table2.BrID连接

换句话说,从第一行开始。

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)

这应该是结果表2:

ID    Name        BrID    IDt2
------------------------------
11    OthName11   Br1     22
22    HQName111   HQ1
33    HQName222   HQ2
44    OthName22   Br2     22
55    OthName33   Br3     33

是否可以在一个UPDATE中进行? 我怎么能这样做?

5 个答案:

答案 0 :(得分:4)

您只需要多个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

答案 1 :(得分:2)

试试这个:

UPDATE A 
SET A.IDt2 = A1.ID 
FROM table2 A 
INNER JOIN table1 T1 ON A.BrID = T1.BrId 
INNER JOIN table2 A1 ON T1.HQID = A1.BrId;

答案 2 :(得分:0)

只需将查询作为子查询写入第三个查询UPDATE Table2 SET IDt2 = (SELECT ID WHERE...),依此类推......

答案 3 :(得分:0)

检查一下..

UPDATE t2
SET    t2.IDt2 = t1.ID
FROM   table2 t2
       JOIN (
                SELECT t1.BrID,
                       t1.HQID,
                       t2.ID
                FROM   table1 t1
                       LEFT OUTER JOIN table2 t2
                            ON  t2.BrID = t1.HQID
            ) t1
            ON  t2.BrID = t1.BrID

答案 4 :(得分:0)

试试这个:

UPDATE  T2
SET     T2.IDt2 =  (SELECT T3.ID
                    FROM   Table1 T1 INNER JOIN
                           Table2 T3 ON T3.BrID = T1.HQID
                    WHERE  T2.BrID = T1.BrID)
FROM    Table2 T2