關聯表更新

喵了個咪同學發表於2019-01-21

Oralce和DB2都支援的語法:

UPDATE A SET (A1, A2, A3) = (SELECT B1, B2, B3 FROM B WHERE A.ID = B.ID)
複製程式碼

MS SQL Server不支援這樣的語法,相對應的寫法為:

UPDATE A  SET A1 = B1, A2 = B2, A3 = B3  FROM A LEFT JOIN B ON A.ID = B.ID
複製程式碼

個人感覺MS SQL Server的Update語法功能更為強大。MS SQL SERVER的寫法:

UPDATE A SET A1 = B1, A2 = B2, A3 = B3 FROM A, B WHERE A.ID = B.ID
複製程式碼

在Oracle和DB2中的寫法就比較麻煩了,如下:

UPDATE A SET (A1, A2, A3) = (SELECT B1, B2, B3 FROM B WHERE A.ID = B.ID)
WHERE ID IN (SELECT B.ID FROM B WHERE A.ID = B.ID)
複製程式碼

或者

update test_a a set (a.name,a.age)= (select b.name,b.age from test_b b where a.id = b.id) 
where exists (select * from test_b c where c.id=a.id)
複製程式碼

相關文章