如何从没有重复的另一个表中选择?

时间:2018-09-02 18:17:15

标签: mysql sql database join select

我有这样的查询:

SELECT activity.login_time, sum(activity.sessions) FROM activity 
inner JOIN payments ON payments.user_id = activity.user_id
WHERE activity.login_time BETWEEN '2018-04-05' and '2018-04-18' 
GROUP BY activity.login_time;

我有两个表(列:活动(用户ID,会话,登录时间)和付款(列:用户ID),第二个表具有重复值。 需要从“付款”中选择不重复的user_id会话。

我的变体无法避免重复。我应该在查询中解决什么?

谢谢!

activity
user_id login_time  sessions
101 2018-04-11  4
102 2018-04-02  1
103 2018-04-15  3
104 2018-04-06  2
104 2018-04-05  6
105 2018-04-16  1
105 2018-04-04  6
105 2018-04-01  14
106 2018-04-19  5
106 2018-04-17  3
106 2018-04-16  3
106 2018-04-15  4
106 2018-04-13  2

付款

user_id
101
103
104
106

输出

login_time  sessions
2018-04-05  ?
2018-04-06  ?
2018-04-07  ?
2018-04-08  ?
2018-04-09  ?
2018-04-10  ?
2018-04-11  ?
2018-04-12  ?
2018-04-13  ?
2018-04-14  ?
2018-04-15  ?
2018-04-16  ?
2018-04-17  ?
2018-04-18  ?

1 个答案:

答案 0 :(得分:0)

在您的描述中,我似乎希望用户聚合

    SELECT 
        a.user_id,
        SUM(a.sessions) as user_session
    FROM 
        activity a
    INNER JOIN 
        payments p ON p.user_id = a.user_id
    WHERE 
        a.login_time BETWEEN '2018-04-05' AND '2018-04-18' 
    GROUP BY 
        a.user_id;

但是,如果要使用每个用户总和的登录日期,请使用子查询

SELECT
    a1.login_time, t1.user_session  
FROM
    activity a1 
INNER JOIN
    (SELECT 
         a.user_id,
         AVG(a.sessions) AS user_session
     FROM 
         activity a
     INNER JOIN 
         payments p ON p.user_id = a.user_id
     WHERE 
         a.login_time BETWEEN '2018-04-05' AND '2018-04-18' 
     GROUP BY 
         a.user_id) AS t1 ON a1.user_id = t1.user_id