如何在MySQL中对多个表进行“分组依据”

时间:2019-09-16 06:49:25

标签: mysql sql

我有两个桌子。

 1. Users (id,name,createdAt)

 2. Images (id,createdAt)

我想生成类似这样的报告

date       | newUsers | newImages
2019-09-12 | 12       | 3
2019-09-13 | 15       | 5
2019-09-14 | 16       | 8

我到目前为止所做的是

SELECT 
    u.newUsers,
    i.newImages
FROM
    (SELECT 
        COUNT(*) AS newUsers,createdAt
    FROM
        users group by date(createdAt)) u
        left join
        (select count(*) as newImages,createdAt from images group by date(createdAt)) i

不幸的是,这有一个语法错误。

如何使用achieve mysql? 我也在使用Server version: 5.7.27-0ubuntu0.18.04.1 (Ubuntu)

3 个答案:

答案 0 :(得分:1)

您缺少on子句

   select 
        u.newUsers,
        i.newImages,
        u.createdAt
    from
        (select
            count(*) AS newUsers
            , date(createdAt) as createdAt
        from
            users 
        group by date(createdAt)) u
    left join
         (select count(*) as newImages
             , date(createdAt) as createdAt
        from images 
        group by date(createdAt)) i
    on i.createdAt = u.createdAt

答案 1 :(得分:0)

您可以尝试以下方式-

SELECT u.createdAt,COUNT(*) AS newUsers,count(*) as newImages
FROM users u left join images i on u.createdAt=i.createdAt
left join 
group by u.createdAt

答案 2 :(得分:0)

如果您想确保自己没有错过任何日期,那么left join是不够的。一种方法是union all / group by

select date, sum(is_user) as num_users, sum(is_image) as num_images
from ((select date(createdat) as date, 1 as is_user, 0 as is_image
       from users
      ) union all
      (select date(createdat) as date, 0 as is_user, 1 as is_image
       from images
      ) 
     ) ui
group by date;