2017-06-29 60 views
0

我有這樣的,我需要過濾的鍵和檢索鍵的名單表。如何檢索包含和排除特定密鑰的列表?

id key 
1 1 
1 2 
1 3 
1 4 
2 1 
2 3 
3 1 
3 4 
4 1 
4 4 

所需的輸出:

id key 
2 1 
2 3 
3 1 
3 4 

在這裏,我想ID即(2,3),其中關鍵的1存在和關鍵2缺少的列表。

+0

請澄清 「其中1是有和2不存在。」據「所需輸出」一節中,我會寫一個WHERE子句,如「where id> 1及ID <4」,但我覺得可能不會解決你所有的案件 – RemedialBear

+0

@ChirayuChamoli。 。 。 ID = 3沒有鑰匙= 1 –

回答

1

這回答是問這個問題:「在這裏,我想ID列表。在這關鍵1存在和關鍵2缺失。」

您可以使用existsnot exists

select t.* 
from t 
where exists (select 1 from t t2 where t2.id = t.id and t2.key = 1) and 
     not exists (select 1 from t t2 where t2.id = t.id and t2.key = 2); 

如果你只是想IDS,那麼我更喜歡聚集和having

select id 
from t 
group by id 
having sum(case when key = 1 then 1 else 0 end) > 0 and 
     sum(case when key = 2 then 1 else 0 end) = 0; 
+0

這工作得很好,它給了我不同的ID,但是當我指望他們我得到全1。任何想法?還有一點解釋會很棒。 –

+0

你使用'sum()'或'count()'? –

+0

我試着用count,然後它給我所有的ID爲1。 –

0

假設你的表名是 '測試',然後爲根據你提到的輸出SQL查詢將

SELECT * FROM testing WHERE key!= 2和id在(2,3)

相關問題