2012-04-15 45 views
3

我有一個表,它看起來像:如何在行組上執行'WHERE'?

+-----------+----------+ 
+ person_id + group_id + 
+-----------+----------+ 
+ 1  + 10 + 
+ 1  + 20 + 
+ 1  + 30 + 
+ 2  + 10 + 
+ 2  + 20 + 
+ 3  + 10 + 
+-----------+----------+ 

我需要一個查詢,使得僅返回與組10和20以及30 person_ids(僅PERSON_ID:1)。我不知道如何做到這一點,因爲從我所看到的情況來看,這需要我通過person_id對行進行分組,然後選擇包含所有group_ids的行。

我正在尋找的東西,將保留使用密鑰,而不訴諸字符串操作group_concat()等。

+0

'WHERE GROUP_ID IN(10,20,30)' – kirilloid 2012-04-15 23:09:25

+2

@kirilloid,這將仍然返回所有人 – 2012-04-15 23:09:45

+0

我明白了。 AFAIK,只有這樣做的方法:使用多個JOIN – kirilloid 2012-04-15 23:11:31

回答

5

這是你在找什麼:

select person_id from t 
where group_id in (10, 20, 30) 
group by person_id 
having count(distinct group_id) = 3 

雖然有效,使用此解決方案的值的數量,在in將有以匹配您比較計數的值。

以及剛剛換有趣的解決方案,如你所說,即使有group_concat就可以解決這個問題:P

select person_id from t 
where group_id in (10, 20, 30) 
group by person_id 
having group_concat(distinct group_id order by group_id) = '10,20,30' 
+1

+1,這是更好的解決方案。 – 2012-04-15 23:19:55

+0

謝謝:)我希望你不是在談論'group_concat'的東西:P – 2012-04-15 23:27:25

+0

;-)不同的group_id對零維護查詢至關重要。 – 2012-04-15 23:33:23

-2
SELECT person_id FROM... WHERE group_id IN(10,20,30) group by person_id 
having count(*) = 3 
+0

這將執行一個OR對group_id – Drew 2012-04-15 23:12:47

+0

啊對不起,你只想要它得到它person_id = 1 以及SELECT person_id FROM ... WHERE person_id = 1 AND WHERE group_id IN(10,20,30) – AdrianObel 2012-04-15 23:17:38

5

集團和點擊數:

select person_id 
    from ATable 
where group_id IN (10, 20, 30) 
group by person_id 
having count(*) = 3