SQL:基于其他表列从表中选择

SQL:基于其他表列从表中选择,sql,sql-server,Sql,Sql Server,我花了很多时间试图解决这个问题,但没有找到解决办法。 下面是我的桌子。我想做的是,当t1和t2之间的PO、SKU、LOC和REC匹配时,从t1中删除。t2.ST为D,但t1中应存在相同的PO、SKU、LOC,ASN不为空 t1 t2 从上面看,我应该能够删除t1中的第二行,因为第一行相同的PO、SKU、LOC exist和ASN不为空 谢谢。听起来像: delete from t1 where (t1.po,t1.sku,t1.loc,t1.rec) in (select t2.po,t2

我花了很多时间试图解决这个问题,但没有找到解决办法。 下面是我的桌子。我想做的是,当t1和t2之间的PO、SKU、LOC和REC匹配时,从t1中删除。t2.ST为D,但t1中应存在相同的PO、SKU、LOC,ASN不为空

t1

t2

从上面看,我应该能够删除t1中的第二行,因为第一行相同的PO、SKU、LOC exist和ASN不为空

谢谢。

听起来像:

delete from t1
where (t1.po,t1.sku,t1.loc,t1.rec) in 
  (select t2.po,t2.sku,t2.loc,t2.rec
   from t2
   where t2.st = 'D')
and exists (select * from t1 t1_2
            where t1_2.po  = t1.po
            and   t1_2.sku = t1.sku
            and   t1_2.loc = t1.loc
            and   t1_2.asn is not null);

对你的问题的字面解释会变成两个句子:


我不是100%确定这是您真正想要的-它将删除所有匹配的行。如果这不是你想要的,那么你应该问另一个问题。这个问题已经有了答案,以使答案无效的方式更改问题是不礼貌的。

是的,但REC不匹配…您到底想要什么???您能给我们看一下您的SQL代码吗?我本来会显示代码的,但我上面给出的示例是我自己的代码的更简单版本。真正的代码更复杂。谢谢你抽出时间@杰姆博尼克。@Kostis我已经改变了你的顾虑。是的,现在REC是一样的。但我得到了我的答案。非常感谢。
PO |SKU |LOC |ASN   |REC |ST
a    b    c   NULL    g   D
delete from t1
where (t1.po,t1.sku,t1.loc,t1.rec) in 
  (select t2.po,t2.sku,t2.loc,t2.rec
   from t2
   where t2.st = 'D')
and exists (select * from t1 t1_2
            where t1_2.po  = t1.po
            and   t1_2.sku = t1.sku
            and   t1_2.loc = t1.loc
            and   t1_2.asn is not null);
delete t1
    where exists (select 1 
                  from t2
                  where t2.PO = t1.PO and t2.SKU = t1.SKU and
                        t2.LOC = t1.LOC and t2.REC = t1.REC and
                        t2.ST = 'D'
                 ) and
           exists (select 1
                   from t1 tt1
                   where tt1.PO = t1.PO and tt1.SKU = t1.SKU and
                         tt1.LOC = t1.LOC and tt1.asn is not null
                  );