[英]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.