我有表T1,列C1,C2和表T2,列C3,C4,C5。我想删除T1中的记录,其中C1 = C3和C2 = C4,C5 ='123'。我试过的查询是什么
DELETE FROM T1 WHERE (C1,C2) = SELECT (C3,C4) FROM T2 WHERE C5 = '123'
但这不起作用。
答案 0 :(得分:10)
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';
答案 1 :(得分:5)
您可以使用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
更好,因为NULL会导致后者以奇怪的方式执行行为。
答案 2 :(得分:1)
SQL Server在DELETE语句中支持额外的FROM子句。
DELETE FROM T1
FROM T1
INNER JOIN T2
ON T1.c1 = T2.c3
AND T1.c2 = T2.c4
WHERE c5 = '123';