繁体   English   中英

排除在另一行中找不到列中的值的行

[英]Exclude 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的对应行。

试试这个: 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 

这是一个使用不存在的解决方案,该解决方案应该比左外部联接更快(请参阅: 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM