簡體   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