2013-07-26 56 views
4

鏈接顯示記錄我有一個表與兩個ID

ID NAME 
-------- 
1 AAA 
2 BBB 
2 AAA 
2 CCC 
1 DDD 
2 DDD 

我不得不顯示與兩個編號1和2

NAME 
---- 
AAA 
DDD 

我使用下面的查詢鏈接的記錄 -

Select Name from table1 where ID IN (1,2); 

但它顯示我 -

NAME 
----- 
AAA 
BBB 
CCC 
DDD 

如何更改我的查詢來解決此問題?

+4

+1儘管是解決一個很簡單的問題,這個問題形成良好並表現出足夠的努力。 –

回答

6
SELECT DISTINCT NAME 
FROM tabel1 t1 
join table1 t2 
on t1.id = 1 and t2.id = 2 and t1.name = t2.name 

,或者如果可以有很多比賽

SELECT DISTINCT NAME 
FROM tabel1 t1 
WHERE EXISTS (SELECT 1 FROM table1 t2 WHERE t1.name = t2.name and t2.id = 2) 
and t1.id = 1 

SELECT NAME FROM tabel1 WHERE id = 1 
INTERSECT 
SELECT NAME FROM tabel1 WHERE id = 2 
+0

哇,謝謝,這真的很有幫助。很多方面,從來沒有想過這個。非常感謝。 – akhil

1
Select Name 
from table1 
where ID IN (1,2) 
and Name in (select Name    
       from table1 
       where ID IN (1,2) 
       group by Name 
       having count(id) =2 
      ) ; 
2

您需要按名稱進行分組,然後計算您希望過濾的不同ID。

select name 
from table 
where id in (1,2) 
group by name 
having count (distinct ID) = 2 
1
Select Name from TableName 
where id in (1,2) 
group by Name having Count(Distinct Id)>1 
+0

雖然此查詢可能會解決此特定數據集的問題,但恐怕它可能無法用於複雜數據集。 –

+0

@STTLCU對不起,我沒有得到你? –

+0

對不起,我的錯誤我誤解了你的查詢。 –

1
select name 
from table t 
where id = 1 and exists 
(select 1 from table where name = t.name and id = 2)