在一个查询中联接几个表(包括子查询)会更好吗?

时间:2018-09-05 18:45:11

标签: mysql sql database join select

在一个查询中结合几个表(包括后代)会更好吗?

例如,我有2个表:活动(用户ID,登录时间)和付款(用户ID,付款时间,金额)。两个表都得出重复的ID。

任务是选择唯一的user_id,该用户有偿使用,login_time从05.04.12到10.04.12。然后按合计的总金额进行分组。

我的查询是:

SELECT t.diapason, COUNT(*) AS 'number_of_users'
FROM (SELECT CASE  
    when amount<100 then '0-100' 
    when amount>=100 then '100 +' END AS diapason
    FROM 
        (SELECT SUM(amount) AS amount 
        FROM payments GROUP BY payments.user_id) p) t
  GROUP BY t.diapason
  ORDER BY number_of_users desc;

我不知道在“ 2012-04-05”和“ 2012-04-10”之间应该使用“内部联接a ....”

请帮助,谢谢!

数据示例

activity
user_id    login_time
1          05.04.2012
2          05.04.2012
3          06.04.2012
4          30.05.2012

payments
user_id    amount   payment_time
1          50       10.12.2011
1          20        09.12.2011
2          400        08.08.2011

Output for period 05.04.2012-10.04.2012

diapason     number_of_users
0-100          2
100+           1

1 个答案:

答案 0 :(得分:1)

我相信这可以为您提供所需的东西(多种方式之一):

SELECT t.diapason, COUNT(*) AS 'number_of_users'
FROM (SELECT CASE  
    when amount<100 then '0-100' 
    when amount>=100 then '100 +' END AS diapason
    FROM 
        (SELECT SUM(amount) AS amount 
        FROM payments 
        INNER JOIN (SELECT DISTINCT user_id FROM activity where login_time between '2012-04-05' and '2012-04-12') AS a ON payments.user_id = a.user_id
        GROUP BY payments.user_id) AS P
      ) t
GROUP BY t.diapason
  ORDER BY number_of_users desc
;