如何"合并"按日期两个结果集

时间:2014-09-29 14:47:47

标签: mysql sql join

我正在尝试合并以下两个SQL查询的结果:

上传表格

SELECT DATE(`timestamp`), SUM(uploaded) AS total_upload FROM uploads;

date          total_download

2014-09-11    1000
2014-09-12    1000
2014-09-13    1000

下载表格

SELECT DATE(`timestamp`), SUM(downloaded) AS total_download FROM downloads;

date          total_upload

2014-09-09    1000
2014-09-10    1000
2014-09-11    1000

我希望得到以下结果,如果没有上传则没有下载和空白结果会显示空白结果:

date          total_download   total_upload

2014-09-09                     1000
2014-09-10                     1000
2014-09-11    1000             1000
2014-09-12    1000
2014-09-13    1000

我以为我可以在download_date = upload_date上加入表格,但显然没有上传的日子会丢失。我如何正确地合并这些结果?

1 个答案:

答案 0 :(得分:1)

FULL JOINCOALESCE()一起使用。

SELECT COALESCE(u.date, d.date) AS date,
    u.total_upload AS total_upload,
    d.total_download as total_download
FROM (SELECT DATE(`timestamp`) AS date, SUM(uploaded) AS total_upload FROM uploads) as u
FULL OUTER JOIN (SELECT DATE(`timestamp`) AS date, SUM(downloaded) AS total_download FROM downloads) as d
    ON u.date = d.date

语法可能会关闭;我对MySQL很生气。

编辑:如果您想要完全空白,则需要替换:COALESCE(CAST(u.total_upload AS varchar),'') AS total_upload或类似内容。但请注意,这实际上会将输出数据类型更改为字符。