合并2表和GROUP BY日期

时间:2015-07-18 17:56:01

标签: mysql merge group-by

我需要在日期的中按计数基数合并多个表格组。

以下是我的表结构:

#table1
id date
1  2015-07-01 00:00:00
2  2015-07-02 00:00:00
3  2015-07-03 00:00:00

#table2
id date
1  2015-07-02 00:00:00
2  2015-07-02 00:00:00
3  2015-07-02 00:00:00
4  2015-07-10 00:00:00

我想要实现的目标:

#query result
date       t1_count   t2_count
2015-07-01 1          NULL
2015-07-02 1          3
2015-07-03 1          NULL
2015-07-10 NULL       1

以下是我的查询,引用此link

SELECT left(A.date,10) AS `day`
     , COUNT(A.ID) AS `a_count`
     , COUNT(B.ID) AS `b_count`
  FROM table1 A

 LEFT JOIN table2 B
    ON LEFT(A.date,10) = LEFT(B.date,10)
 GROUP BY LEFT(A.date,10)

UNION

SELECT left(B.date,10) AS `day`
     , COUNT(A.ID) AS `a_count`
     , COUNT(B.ID) AS `b_count`
  FROM table1 A

 RIGHT JOIN table2 B
    ON LEFT(A.date,10) = LEFT(B.date,10)

 GROUP BY LEFT(A.date,10);

但结果是

#query result
date       t1_count   t2_count
2015-07-01 1          0
2015-07-02 3          3
2015-07-03 1          0
2015-07-10 0          1

我尝试修改并搜索其他解决方案,如UNION ALL,LEFT JOIN等,但我没有运气来解决这个问题。

1 个答案:

答案 0 :(得分:1)

您可以使用union allgroup by

执行此操作
select date, sum(istable1) as numtable1, sum(istable2) as numtable2
from ((select date(date) as date, 1 as istable1, NULL as istable2
       from table1
      ) union all
      (select date(date) as date, NULL as istable1, 1 as istable2
       from table2
      )
     ) t
group by date
order by 1;

在某些情况下,也可以更快地聚合子查询中的数据:

select date, sum(numtable1) as numtable1, sum(numtable2) as numtable2
from ((select date(date) as date, count(*) as numtable1, NULL as numtable2
       from table1
       group by date(date)
      ) union all
      (select date(date) as date, NULL as numtable1, count(*) as numtable2
       from table2
       group by date(date)
      )
     ) t
group by date
order by 1;

如果您希望在所需结果中使用0而不是NULL,请在子查询中使用0代替NULL