如何删除多列IN \ NOT IN其他表的位置?

时间:2019-02-13 09:34:18

标签: sql sql-server

我有一个目标表和一个源表

并且仅当某些列的数据出现在另一个表(源表)中时,我才想从其中删除行

例如:

要从中删除的目标表:

|  Delivery  |   Order     |     Row      |  OtherColumn |
|:----------:|:-----------:|:------------:|:------------:|
|     1      |     A       |    000010    |     asaf     |
|     1      |     A       |    000020    |     ag       |
|     2      |     C       |    000010    |     DEL      |<-I WANT TO DELETE THIS ROW
|     2      |     D       |    000020    |     hhs      |  
|     3      |     E       |    000040    |     ba       |
|     3      |     E       |    000170    |     ass      |

源表,在这里我要在目标表中保留一行:

|  Delivery  |   Order     |     Row      |
|:----------:|:-----------:|:------------:|
|     2      |     D       |    000020    | 

我正在寻找目标表的结果是:

|  Delivery  |   Order     |     Row      |  OtherColumn |
|:----------:|:-----------:|:------------:|:------------:|
|     1      |     A       |    000010    |     asaf     |
|     1      |     A       |    000020    |     ag       |
|     2      |     D       |    000020    |     hhs      |  
|     3      |     E       |    000040    |     ba       |
|     3      |     E       |    000170    |     ass      |

意思是,如果交货编号2的所有行不在源表中,则它们将被删除

我的Delivery参数为@Delivery

我尝试的是:

delete from Target 
where Delivery = @Delivery
and ([Delivery],[Order],[Row]) not in (select [Delivery],[Order],[Row] 
                                 from Source)

但是有语法错误,我知道NOT IN运算符不能接受多个列,

我该怎么办?

2 个答案:

答案 0 :(得分:2)

尝试使用“不存在”:

delete from Target 
from Target target
where Delivery = @Delivery
and NOT EXISTS (select 1 from Source s where s.[Delivery] = target.Delivery and 
    s.[Order] = target.[Order] and s.[Row] = target.[Row] )

答案 1 :(得分:1)

您可以尝试以下查询吗?

DELETE from Target WHERE Delivery = @Delivery AND NOT EXists(SELECT 1 from Source 
WHERE Delivery =Target.Delivery AND Order=Target.Order and Row=Target.Row )