简体   繁体   English

mysql-计算两个表中的行

[英]mysql - count rows from two tables

so i have this tables 所以我有这张桌子

log_in 登录

+---------+------------+---------+
| date_id | date_today | user_id |
+---------+------------+---------+
|    1    | 2017/03/19 |    16   |
|    2    | 2017/03/20 |    17   |
|    3    | 2017/03/20 |    12   |
|    4    | 2017/03/21 |    16   |
|    5    | 2017/03/22 |    10   |
|    6    | 2017/03/22 |    11   |
+---------+------------+---------+

file_downloads file_downloads

+---------+------------+---------+
| date_id | date_today | user_id |
+---------+------------+---------+
|    1    | 2017/03/20 |    17   |
|    2    | 2017/03/20 |    17   |
|    3    | 2017/03/20 |    12   |
|    4    | 2017/03/20 |    17   |
|    5    | 2017/03/20 |    12   |
|    6    | 2017/03/20 |    12   |
|    7    | 2017/03/20 |    12   |
|    8    | 2017/03/20 |    12   |
|    9    | 2017/03/22 |    10   |
|    10   | 2017/03/22 |    10   |
|    11   | 2017/03/22 |    11   |
+---------+------------+---------+

and this is my desired result: 这是我想要的结果:

+------------+-----------+--------+
| date_today | login_num | dl_num |
+------------+---------+----------+
| 2017/03/19 |     1     |   0    |
| 2017/03/20 |     2     |   8    |
| 2017/03/21 |     1     |   0    |
| 2017/03/22 |     2     |   3    |
+------------+-----------+--------+

i am still new to mysql so any help would be much appreciated. 我还是mysql的新手,所以将不胜感激。 thank you! 谢谢! :) :)

I think the easiest way is union all and group by : 我认为最简单的方法是将union all group by union allgroup by

select date_today, sum(login) as logins, sum(dl) as dls
from ((select date_today, 1 as login, 0 as dl from log_in
      ) union all
      (select date_today, 0, 1 from file_downloads
      )
     ) lfd
group by date_today;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM