我有一个如下查询:
SELECT table1.time, table1.co, table2.co_ro
FROM(
SELECT p1.time, SUM(p1.kpi_0) AS co
FROM hourly_history p1
WHERE p1.type_id=3
GROUP BY p1.time) AS table1,(
SELECT p2.time, SUM(p2.kpi_0) AS co_ro
FROM hourly_history p2
WHERE p2.type_id=5
GROUP BY p2.time) AS table2
WHERE table1.time=table2.time
如果type_id = 3存在数据,而对于特定时间值(例如12-10-2011 12:00:00),type_id = 5不存在,则结果集中不存在该行的时间预期
我需要一个返回特定时间行的查询,即使type_id = 5也没有数据。我怎么写这样的查询?
提前致谢。
答案 0 :(得分:0)
执行此操作的基本方法是创建一个包含所有应存在的时间的表,然后对其进行连接。然后,您的缺失值将变为空值,您可以使用COALESCE
填充默认值。
带有时间的表不必是基表。它可以通过将日,小时和分钟表连接在一起构建,作为视图或作为查询的一部分。
尽管如此,在您的示例查询中,可能通过从内部联接切换到左联接来获得您想要的内容。遗憾的是,MySQL没有完全外连接。
答案 1 :(得分:0)
这个概念应该有用(虽然我没有测试过这些查询):
SELECT t1, sum(co), sum(co_ro)
FROM
(
(
SELECT p1.time AS t1, SUM(p1.kpi_0) AS co, 0 AS co_ro
FROM hourly_history p1
WHERE p1.type_id=3
GROUP BY p1.time
)
UNION ALL
(
SELECT p2.time AS t1, 0 AS co, SUM(p2.kpi_0) AS co_ro
FROM hourly_history p2
WHERE p2.type_id=5
GROUP BY p2.time
)
)
GROUP BY t1;
这应该更简单:
SELECT t1, sum(co), sum(co_ro)
FROM
(
(
SELECT p1.time AS t1, p1.kpi_0 AS co, 0 AS co_ro
FROM hourly_history p1
WHERE p1.type_id=3
)
UNION ALL
(
SELECT p2.time AS t1, 0 AS co, p2.kpi_0 AS co_ro
FROM hourly_history p2
WHERE p2.type_id=5
)
)
GROUP BY t1;