【问题标题】:Exclude rows where value in column not found in another row排除在另一行中找不到列中的值的行
【发布时间】:2014-07-17 08:59:41
【问题描述】:

这是上一个问题对上一个问题的后续,但与Find rows where value in column not found in another row相反

给定一张表Table1,列Key1 (int), Key2 (int), and Type (varchar)...

我想排除任何两行 Type 等于 'TypeA'Key2Null 在表中有相应的行 Type 等于 'TypeB'Key2 等于 Key1 来自另一行。

所以,给定数据

**KEY1**     **Key2**     **Type**
   1           NULL         TypeA
   2           5            TypeA
   3           1            TypeB
   4           NULL         TypeA
   5           NULL         TypeB
   6           26           TypeC
   7           NULL         TypeD
   8           NULL         TypeD

我想返回除 Key=1 和 Key=3 之外的所有行,因为这些行一起满足 Type='TypeA'/Key2=NULL 的条件,并且确实有对应的行 Type='TypeB'/ Key1=Key2。

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    试试这个:http://sqlfiddle.com/#!6/fffcb/2

    select a.*
    from demo a
    left outer join demo b
    on 
    (
      b.key2 = a.key1
      and a.[Type] = 'TypeA'
      and b.[Type] = 'TypeB'
      and a.Key2 is null
    )
    or
    (
      b.key1 = a.key2
      and b.[Type] = 'TypeA'
      and a.[Type] = 'TypeB'
      and b.Key2 is null
    )
    where b.key1 is null 
    

    【讨论】:

      【解决方案2】:

      这是一个使用 not exists 的解决方案,它应该比左外连接更快(参见:http://sqlinthewild.co.za/index.php/2010/03/23/left-outer-join-vs-not-exists/)。

      SELECT *
      FROM demo d1
      WHERE NOT ((TYPE LIKE 'TypeA'
                  AND Key2 IS NULL
                  AND EXISTS
                    (SELECT 1
                     FROM demo d2
                     WHERE d2.TYPE='TypeB'
                       AND d2.Key2 = d1.key1))
                 OR (TYPE LIKE 'TypeB'
                     AND Key2 IS NOT NULL
                     AND EXISTS
                       (SELECT 1
                        FROM demo d2
                        WHERE d2.TYPE='TypeA'
                          AND d2.Key1 = d1.key2)));
      

      您应该在 key1 和 key2 上有索引。

      CREATE INDEX index_key1
      ON demo (key1);
      
      CREATE INDEX index_key2
      ON demo (key2);
      

      【讨论】:

        猜你喜欢
        • 2022-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-30
        • 1970-01-01
        相关资源
        最近更新 更多