mysql - 计算两个表中的行数

时间:2017-03-23 02:29:00

标签: mysql

所以我有这张桌子

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

+---------+------------+---------+
| 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   |
+---------+------------+---------+

这是我想要的结果:

+------------+-----------+--------+
| 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    |
+------------+-----------+--------+

我还是mysql的新手,所以任何帮助都会非常感激。谢谢! :)

1 个答案:

答案 0 :(得分:0)

我认为最简单的方法是group byselect 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;

{{1}}