SQL Server - 使用子查询帮助删除具有多个where子句的行

时间:2011-11-23 15:50:08

标签: sql sql-server

我在删除SQL时遇到了一些麻烦。 SQL Server不喜欢在where子句中有多个参数来从table_02中删除行(子查询是表1)。对此有任何帮助将非常感激。

感谢。

DELETE FROM table_02
        WHERE (col_1,col_2,col_3,col_4)
        IN (            
            SELECT col_1,col_2,col_3,col_4 
                    FROM table_01
                    GROUP BY
                    col_1,col_2,col_3,col_4
                    HAVING SUM(CASE WHEN col_1<6 THEN col_2*-1 ELSE col_2 END)=0
           )

2 个答案:

答案 0 :(得分:5)

您可以将IN重写为EXISTS

DELETE 
FROM table_02
WHERE  EXISTS(SELECT *
              FROM   table_01
              WHERE  table_02.col_1 = table_01.col_1
                     AND table_02.col_2 = table_01.col_2
                     AND table_02.col_3 = table_01.col_3
                     AND table_02.col_4 = table_01.col_4
              HAVING SUM(CASE
                           WHEN col_1 < 6 THEN col_2 * -1
                           ELSE col_2
                         END) = 0)  

答案 1 :(得分:1)

Delete a  
from table1 a 
Inner Join table2 b 
on  a.col = b.col 
WHERE ...