gpt4 book ai didi

mysql - 合并 2 个表和 GROUP BY 日期

转载 作者:行者123 更新时间:2023-11-29 12:05:54 25 4
gpt4 key购买 nike

我需要根据日期的计数来合并多个表组。

下面是我的表结构:

#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 等,但我没有运气解决这个问题。

最佳答案

您可以使用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子查询。

关于mysql - 合并 2 个表和 GROUP BY 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31493932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com