mysql选择distinct where子句

时间:2010-11-17 15:36:20

标签: mysql join

我有这个表,我想选择所有不同的user_id值,其中有一个事件='AAAAAAAAAA'和事件='XXXXXXXXXX'(即只有结果应该是user_id = 123456789)

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'

给了我一切。任何建议 - 我猜我需要沿着'加入'路走到这里吗?

5 个答案:

答案 0 :(得分:3)

试试这个:

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

这将选择两个列表(用户为AAA,用户为w / XXX),然后将它们合并在一起,删除重复的行。

希望有所帮助!

谢谢, 乔

答案 1 :(得分: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 :(得分: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

答案 3 :(得分: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'
    )

答案 4 :(得分:0)

我会用这样的东西......

SET @events := 'AAAAAAAAAA,XXXXXXXXXX';

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