我有表T1,列C1,C2和表T2,列C3,C4,C5。我想從T1中刪除記錄,其中C1 = C3 AND C2 = C4和C5 ='123'。什麼將是我試過以下查詢通過連接多列刪除查詢
DELETE FROM T1 WHERE (C1,C2) = SELECT (C3,C4) FROM T2 WHERE C5 = '123'
但這是行不通的。
我有表T1,列C1,C2和表T2,列C3,C4,C5。我想從T1中刪除記錄,其中C1 = C3 AND C2 = C4和C5 ='123'。什麼將是我試過以下查詢通過連接多列刪除查詢
DELETE FROM T1 WHERE (C1,C2) = SELECT (C3,C4) FROM T2 WHERE C5 = '123'
但這是行不通的。
SQL Server中沒有WHERE (x,y) = (a,b)
語法,很抱歉。這是你如何執行刪除,基於連接,無論多少列參與加入:
DELETE t1
FROM t1
INNER JOIN t2
ON t1.c1 = t2.c3
AND t1.c2 = t2.c4
WHERE t2.c5 = '123';
SQL Server支持一個額外的FROM子句DELETE語句。
DELETE FROM T1
FROM T1
INNER JOIN T2
ON T1.c1 = T2.c3
AND T1.c2 = T2.c4
WHERE c5 = '123';
可以使用exists
做到這一點:
DELETE FROM T1
WHERE exists (SELECT 1 FROM T2 WHERE C5 = '123' and t2.c3 = t1.c1 and t2.c4 = t1.c2))
一般情況下,使用exists
比使用in
使用子查詢,因爲空白可導致後者做奇怪的方式行爲更好。