MySQL:具有不同“动作”的查询表

时间:2017-01-04 07:42:42

标签: mysql

这是我目前的表格:

+--------+----------+------------+
| userid | action   | day        |
+--------+----------+------------+
| 123    | play     | 2016-11-06 |
| 123    | purchase | 2016-11-06 |
| 345    | login    | 2016-11-06 |
| 123    | level_up | 2016-11-07 |
| 123    | play     | 2016-10-01 |
| 456    | sign_out | 2016-10-02 |
| 456    | sign_out | 2016-11-02 |
+--------+----------+------------+

我想打印出至少有2个独特操作的userid。 456只有1个不同,所以我不想打印出来。

所以我想打印出来:

+--------+----------+------------+
| userid | action   | day        |
+--------+----------+------------+
| 123    | play     | 2016-11-06 |
| 123    | purchase | 2016-11-06 | 
| 123    | level_up | 2016-11-07 |
| 123    | play     | 2016-10-01 | 
+--------+----------+------------+

这是我最好的尝试:

SELECT userid as this_id

FROM sampleTable WHERE (

SELECT COUNT(DISTINCT action) 
     FROM sampletable
    WHERE userid = this_id) 
     >= 2;

1 个答案:

答案 0 :(得分:3)

您需要先为每个用户计算不同的action。然后在inner join的帮助下,您可以获得所需的行。

SELECT 
 *
FROM your_table YT 
INNER JOIN 
(
    SELECT 
     userid
    FROM your_table 
     --Add your where clause here 
    GROUP BY userid
    HAVING COUNT(DISTINCT action) >= 2
) AS t
ON t.userid = YT.userid;

编辑:

回应你的评论

SELECT 
 *
FROM your_table YT 
INNER JOIN 
(
    SELECT 
     userid
    FROM your_table 
    WHERE action IN ('play', 'level_up')
    GROUP BY userid
    HAVING COUNT(DISTINCT action) = 2
) AS t
ON t.userid = YT.userid;