我有两个数据库,有两个相似的表:
数据库1
id date value
--- ----------- ---------
1 2016-04-20 900
2 2016-05-02 455
3 2016-05-03 90
4 2016-05-02 855
数据库2
SELECT date, SUM(value) As TOTAL FROM tablename
WHERE date >= DATE_SUB( NOW( ) , INTERVAL 1 YEAR )
GROUP BY date ORDER BY date
我对每个数据库都有这个查询:
Database1 Database2
date TOTAL date TOTAL
------ --------- ------- -------
2016-05-01 234 2016-04-20 900
2016-05-02 567 2016-05-02 1310
2016-05-03 1100 2016-05-03 90
返回以下结果:
Cobined Results
date TOTAL_DB1 TOTAL_DB2
------ --------- ----------
2016-04-20 0 900
2016-05-01 234 0
2016-05-02 567 1310
2016-05-03 1100 90
现在我想要一个根据日期结合这两个结果的查询,我的预期输出是:
ActivityManager
答案 0 :(得分:2)
使用union all
,然后按组date
进行聚合:
SELECT `date`, sum(TOTAL_DB1) as TOTAL_DB1, sum(TOTAL_DB2) as TOTAL_DB2
FROM (
SELECT date, SUM(value) As TOTAL_DB1, 0 AS TOTAL_DB2 FROM Database1
WHERE date >= DATE_SUB( NOW( ) , INTERVAL 1 YEAR )
GROUP BY date
UNION ALL
SELECT date, 0 AS TOTAL_DB1, SUM(value) As TOTAL_DB2 FROM Database2
WHERE date >= DATE_SUB( NOW( ) , INTERVAL 1 YEAR )
GROUP BY date
) t
GROUP BY `date`
ORDER BY `date`