简体   繁体   中英

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

+---------+------------+---------+
| 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. thank you! :)

I think the easiest way is union all and group 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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