[英]Find rows where value in column not found in another row
似乎无法使此SQL查询正常工作! 我已经搜索了这个问题的答案,尽管有些职位接近,但他们只是怀念而已。
给定一个表Table1
,其中包含列Key1 (int), Key2 (int), and Type (varchar)
...
我想从另一行中获取Type
等于'TypeA'
且Key2
为Null
的表中没有对应行的表,其中Type
等于'TypeB'
且Key2
等于Key1
因此,鉴于数据
**KEY1** **Key2** **Type**
1 NULL TypeA
2 5 TypeA
3 1 TypeB
4 NULL TypeA
5 NULL TypeB
我只想返回Key1 = 4的行,因为该行满足Type ='TypeA'/ Key2 = NULL的条件,并且没有另一行的Type ='TypeB'/ Key1 = Key2的对应行。
我已经尝试过了,但是行不通...
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')
我不是子查询的最大粉丝。
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
我认为这里的逻辑是正确的。 我们使用表1,其中t1.key2为null,t1.type ='typea'...将其自身连接为t2,其中t2.type ='typeb'。 每次找到t2.type b记录时,我们都希望忽略它,因此t2.key1(或任何t2字段)为null。
逻辑有意义吗? 放手,让我知道
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.