Mysql - 将具有不同日期值的两个表与group by组合在一起

时间:2016-12-16 07:08:46

标签: mysql union outer-join

我正在从事项目工作, 我需要每天用户显示获得积分和交换积分。

我有两个不同的表来存储数据。 tables(a,b)如下: 表a:

id   user_id     earned   created_at
--------------------------------------------
1      1          1       2016-12-14
2      2          2       2016-12-14
3      2          1       2016-12-14
4      3          1       2016-12-15

表格b:

id   user_id   exchanged   created_at
--------------------------------------------
1      1          1       2016-12-14
2      1          2       2016-12-14
3      2          1       2016-12-14
4      4          1       2016-12-15
5      3          3       2016-12-16

我想在日期合并两个表格,如下所示

user_id     earned  exchanged    created_at
-------------------------------------------------
  1          1           1        2016-12-14
  2          3           1        2016-12-14
  3          1           0        2016-12-15
  4          0           1        2016-12-15
  3          0           3        2016-12-16

我尝试搜索过,我最终得到以下查询(sqlfiddle):

select user_id, created_at, sum(earned) as earned, sum(exchanged) as exchanged from (
SELECT 
    a.user_id,
    DATE_FORMAT(a.created_at, '%d-%m-%Y') AS created_at,
    a.earned,
    0 AS exchanged
FROM
    a
        LEFT JOIN
    b ON DATE_FORMAT(a.created_at, '%y%m%d') = DATE_FORMAT(b.created_at, '%y%m%d') 
UNION SELECT 
    b.user_id,
    DATE_FORMAT(b.created_at, '%d-%m-%Y') AS created_at,
    0 AS earned,
    b.exchanged
FROM
    a
        RIGHT JOIN
    b ON DATE_FORMAT(a.created_at, '%y%m%d') = DATE_FORMAT(b.created_at, '%y%m%d')
    ) as tbl group by tbl.created_at, tbl.user_id

但是它显示了交换点的错误总和。

2 个答案:

答案 0 :(得分:1)

...试

select user_id, created_at, sum(earned), sum(exchanged) from
((select id, user_id, earned, 0 as exchanged, created_at from a)
union all 
(select id, user_id, 0 as earned, exchanged, created_at from b)) combined
group by user_id, created_at

答案 1 :(得分:0)

更新:只有当每个用户每天都有条目时,此查询才会获取结果。

select ex.user_id, ex.created_at, sum(earned) as earned, sum(exchanged) as exchanged 
from exchanged ex, earned ea 
where ea.created_at = ex.created_at 
and ea.user_id = ex.user_id 
group by user_id, created_at