我有3个收集统计信息的查询:
SELECT
COUNT(id) count,
DATE(created_at) date
FROM t1
GROUP BY
date;
SELECT
COUNT(id) count,
DATE(created_at) date
FROM t2
GROUP BY
date;
SELECT
COUNT(id) count,
DATE(date_started) date
FROM t1
GROUP BY
date;
现在我分别运行这些查询3次以获取这些数据。 有可能将这些组合成1个查询来得到这样的东西吗?
date | count1 | count2 | count3
-------------------------------------
2018-04-25 | 5 | (null) | 2
2018-04-24 | (null) | 3 | 4
答案 0 :(得分:3)
尝试以下
SELECT
`date`,
SUM(count1) count1,
SUM(count2) count2,
SUM(count3) count3
FROM
(
SELECT
DATE(created_at) `date`,
COUNT(id) count1,
NULL count2,
NULL count3
FROM t1
GROUP BY DATE(created_at)
UNION ALL
SELECT
DATE(created_at) `date`,
NULL count1,
COUNT(id) count2,
NULL count3
FROM t2
GROUP BY DATE(created_at)
UNION ALL
SELECT
DATE(date_started) `date`,
NULL count1,
NULL count2,
COUNT(id) count3
FROM t1
GROUP BY DATE(date_started)
) q
GROUP BY `date`
答案 1 :(得分:0)