2010-11-17 133 views
2

我有這張表,我想選擇所有不同的user_id值,其中既有事件='AAAAAAAAAA'和事件='XXXXXXXXXX'(即只有結果應該是user_id = 123456789)mysql select distinct clause

unique_row_id user_id   event  event_timestamp 
---------------------------------------------------------------- 
0    123456789  AAAAAAAAAA 2010-01-20 15:00:00 
1    123456789  abcdefghij 2010-01-20 15:00:05 
2    123456789  XXXXXXXXXX 2010-01-20 15:00:15 
3    987654321  AAAAAAAAAA 2010-01-20 16:00:00 
4    987654321  abcdefghij 2010-01-20 16:00:05 
5    987654321  abcdefghij 2010-01-20 16:00:15 
6    111111111  XXXXXXXXXX 2010-01-20 16:01:00 
7    111111111  XXXXXXXXXX 2010-01-20 16:01:05 
8    111111111  XXXXXXXXXX 2010-01-20 16:01:15 

我都試過:

SELECT distinct user_id from mydata where event='AAAAAAAAAA' and event='XXXXXXXXXX' 

這給了我一個空的結果集,

SELECT distinct user_id from mydata where event='AAAAAAAAAA' or event='XXXXXXXXXX' 

這給了我一切。任何建議 - 我猜我需要沿着'加入'的路走下去嗎?

回答

3

試試這個:

select user_id from mydata where event='AAAAAAAAAAA' 
union 
select user_id from mydata where event='XXXXXXXXXXX'; 

這將選擇兩個列表(用戶瓦特/ AAA,用戶瓦特/ XXX),然後合併在一起,去除重複行。

希望有幫助!

謝謝, 喬

+0

比我正在寫的'SELECT ... WHERE EXISTS(...)'查詢好多了。 ;) – cdhowie 2010-11-17 15:40:29

+1

實際上,這是錯誤的,因爲它確實「不是」而不是「兩個」。現在修改:) – 2010-11-17 15:41:17

+0

選擇不同的USER_ID(從MYDATA 選擇USER_ID其中事件= 'AAAAAAAAAAA' 工會 選擇從MYDATA USER_ID其中事件= 'XXXXXXXXXXX'; ) – 2010-11-17 15:41:55

2

我會用一個子查詢做到這一點:

select distinct user_id 
from mydata m 
where event = 'AAAAAAAAAA' 
and exists (
    select 1 
    from mydata 
    where user_id = m.user_id 
    and event = 'XXXXXXXXXX' 
); 
2

的條件在WHERE子句只適用於在同一時間單行。 爲了檢查兩行,你必須使用JOIN:

SELECT distinct a.user_id 
FROM mydata a, mydata b 
WHERE a.event='AAAAAAAAAA' AND b.event='XXXXXXXXXX' AND a.user_id = b.user_id 

如果你知道一個事件只能出現每個用戶一次,就可以使用GROUP BY:

SELECT user_id 
FROM mydata 
WHERE event in ('AAAAAAAAAA', 'XXXXXXXXXX') 
GROUP BY user_id 
HAVING count(user_id)=2 
0
SELECT 
    DISTINCT user_id 
FROM 
    my_table AS outer_table 
WHERE 
    EXISTS (
     SELECT 
      1 
     FROM 
      my_table AS inner_table_A 
     WHERE 
      inner_table_A.user_id = outer_table.user_id AND 
      inner_table_A.event = 'AAAAAAAAAA' 
    ) AND 
    EXISTS (
     SELECT 
      1 
     FROM 
      my_table AS inner_table_B 
     WHERE 
      inner_table_B.user_id = outer_table.user_id AND 
      inner_table_B.event = 'XXXXXXXXXX' 
    ) 
0

我會用這樣的東西...

SET @events := 'AAAAAAAAAA,XXXXXXXXXX'; 

SELECT user_id 
FROM mydata 
GROUP BY user_id 
HAVING GROUP_CONCAT(DISTINCT event ORDER BY event SEPARATOR ',') = @events;