【问题标题】:SQL mutually exclusive conditionsSQL互斥条件
【发布时间】:2021-11-26 23:43:07
【问题描述】:

编辑:

我有一个表“TableA”,列有product, feature1, feature2 我有另一个表'TableB',列有'saleorder, feature1, feature2'

目前我使用内连接来显示具有匹配列值的产品

SELECT distinct a.product 
FROM TableA a
    INNER JOIN TableB b
    ON a.feature1 = b.feature1 
    AND a.feature2 = b.feature2 
        

目前,这向我显示了 TableA 中与 TableB 中的 feature1、feature2 完全匹配的产品。

我想修改它,以便我看到 TableA 中的那些产品与 feature1、feature2 不匹配。在某种程度上,与原始脚本的输出相反,仅显示那些不存在具有 feature1 和 feature2 的销售订单的产品。

如何使用 T-SQL 做到这一点?

【问题讨论】:

  • WHERE A.feature3 = B.feature3 AND A.feature1 = B.feature1 AND A.feature2 = B.feature2?虽然我真的建议你修复你的设计并使其正常化;你应该有 1 feature 列而不是 3。

标签: sql tsql


【解决方案1】:

如果您不需要 TableB 中的列,可以使用 NOT EXISTS

SELECT DISTINCT product 
FROM TableA p
WHERE NOT EXISTS
(
    SELECT 1
    FROM TableB s
    WHERE s.feature1 = p.feature1 
      AND s.feature2 = p.feature2 
) 

【讨论】:

    【解决方案2】:

    第 1 步:从 TableA 中获取具有特征 1 和特征 2 的所有行,对于 TableA 中没有对应的“特征1”和“特征2”匹配值的行,具有 NULL 的行。

    SELECT A.product,
           A.feature1 Afeature1,
           A.feature2 Afeature2,
           B.feature1 Bfeature1,
           B.feature2 Bfeature2
    FROM   tablea A
           LEFT OUTER JOIN tableb B
                        ON A.feature1 = B.feature1
                           AND A.feature2 = B.feature2;
    

    --- 这将有这样的输出

    product  Afeature1   Afeature2    Bfeature1     Bfeature2 
    abcd     l           l             m             m         
    efgh     x           y             NULL          NULL    -----> this is what you want.
    

    第 2 步:所以现在您只需要从前面的输出中获得的 TableB 中过滤掉 NOT NULL 的列。

    SELECT productA,Afeature1,Afeature2
    FROM   (SELECT A.product productA,
                   A.feature1 Afeature1,
                   A.feature2 Afeature2,
                   B.feature1 Bfeature1,
                   B.feature2 Bfeature2
            FROM   tablea A
                   LEFT OUTER JOIN tableb B
                                ON A.feature1 = B.feature1
                                   AND A.feature2 = B.feature2)
    WHERE  bfeature1 IS  NULL
           AND bfeature2 IS NULL; 
    

    最终输出:

    product  Afeature1   Afeature2     
    efgh     x           y    
    

    【讨论】:

      【解决方案3】:

      from TableA which did not match for feature1 and feature2, but matched for feature3:

      SELECT distinct a.feature3, a.feature1, a.feature2, b.feature1, b.feature2
      FROM TableA a
          INNER JOIN TableB b
          ON a.feature3 = b.feature3  
          AND a.feature1 <> b.feature1
          AND a.feature2 <> b.feature2
      

      【讨论】:

      • 抱歉,我没有正确解释这个问题。我已经对其进行了编辑,以便于解释。
      猜你喜欢
      • 2018-10-27
      • 2018-08-25
      • 2014-11-08
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      • 2018-03-10
      • 2011-01-06
      • 2015-11-17
      相关资源
      最近更新 更多