[英]Find rows where value in column not found in another row
Can't seem to make this SQL query work! 似乎无法使此SQL查询正常工作! I have searched for the answer to this and although some posts come close, they just miss the mark. 我已经搜索了这个问题的答案,尽管有些职位接近,但他们只是怀念而已。
Given one table, Table1
, with columns Key1 (int), Key2 (int), and Type (varchar)
... 给定一个表Table1
,其中包含列Key1 (int), Key2 (int), and Type (varchar)
...
I would like to get the rows where Type
is equal to 'TypeA'
and Key2
is Null
that do NOT have a corresponding row in the table where Type
is equal to 'TypeB'
and Key2
is equal to Key1
from another row 我想从另一行中获取Type
等于'TypeA'
且Key2
为Null
的表中没有对应行的表,其中Type
等于'TypeB'
且Key2
等于Key1
So, given the data 因此,鉴于数据
**KEY1** **Key2** **Type**
1 NULL TypeA
2 5 TypeA
3 1 TypeB
4 NULL TypeA
5 NULL TypeB
I would like to return only the row where Key1 = 4 because that row meets the criteria of Type='TypeA'/Key2=NULL and does not have a corresponding row with Type='TypeB'/Key1=Key2 from another row. 我只想返回Key1 = 4的行,因为该行满足Type ='TypeA'/ Key2 = NULL的条件,并且没有另一行的Type ='TypeB'/ Key1 = Key2的对应行。
I have tried this and it doesn't work... 我已经尝试过了,但是行不通...
SELECT t1.Key1, t1.Key2, t1.Type
FROM Table1 t1
WHERE t1.Key2 IS NULL
AND t1.Type LIKE 'TypeA'
AND t1.Key1 NOT IN
(SELECT Key1
FROM Table1 t2
WHERE t1.Key1 = t2.Key2
AND t1.Key1 <> t2.Key1
AND t2.Type LIKE 'TypeB')
I'm not the biggest fan of where subqueries. 我不是子查询的最大粉丝。
select t1.Key1, t1.Key2, t1.Type
from table1 t1
left join table1 t2
on t1.key1 = t2.key2
and t2.type = 'typeb'
where t1.type = 'typea'
and t1.key2 is null
and t2.key1 is null
I think the logic there is right. 我认为这里的逻辑是正确的。 We are taking table 1 where t1.key2 is null and t1.type = 'typea'...left joining it to itself as t2 where t2.type = 'typeb'. 我们使用表1,其中t1.key2为null,t1.type ='typea'...将其自身连接为t2,其中t2.type ='typeb'。 Every time it finds a t2.type b record, we want to omit it, so where t2.key1 (or any t2 field) is null. 每次找到t2.type b记录时,我们都希望忽略它,因此t2.key1(或任何t2字段)为null。
Logic make sense? 逻辑有意义吗? Give it a run and let me know 放手,让我知道
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.