[英]SQL not exists self-join
我有一张桌子,上面放着所有寄给客户的信件。 我需要运行查询以选择已收到letter_2而不是letter_1的所有account_id。 因此,例如,以下结果应为帐户2和3。
Account_ID Letter_Type
1 Letter_1
1 Letter_2
1 Letter_3
1 Letter_2
2 Letter_2
2 Letter_3
3 Letter_2
提前致谢!
这样做的一个简单的方法,就是用except
:
select account_id
from the_table
where letter_type = 'Letter_2'
except
select account_id
from the_table
where letter_type = 'Letter_1'
使用not exists
的反not exists
看起来像这样:
select t1.account_id
from the_table t1
where t1.letter_type = 'Letter_2'
and not exists (select *
from the_table t2
where t2.letter_type = 'Letter_1' and
and t1.account_id = t2.account_id);
您没有声明您的DBMS,但是上面是标准的ANSI SQL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.