[英]SQL not exists self-join
I've got a table which stores all letters sent out to customers. 我有一张桌子,上面放着所有寄给客户的信件。 I need to run a query to select all account_id's that have received letter_2 but not letter_1.
我需要运行查询以选择已收到letter_2而不是letter_1的所有account_id。 So for example the below results should be accounts 2 & 3.
因此,例如,以下结果应为帐户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
Thanks in advance! 提前致谢!
A straightforward way of doing this, is to use except
: 这样做的一个简单的方法,就是用
except
:
select account_id
from the_table
where letter_type = 'Letter_2'
except
select account_id
from the_table
where letter_type = 'Letter_1'
An anti-join using not exists
would look like this: 使用
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);
You didn't state your DBMS, but the above is standard ANSI SQL 您没有声明您的DBMS,但是上面是标准的ANSI SQL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.