我使用MySQL 5.5并有以下表格和数据
create temporary table test (
t_source float, -- generating time; seconds from midnight
t_received float, -- receiving time; seconds from midnight
delay float -- t_received - t_source
);
insert into test (t_source, t_received, delay) values
(713.27, 714.61, 1.34),
(2791.81, 2797.09, 5.28),
(94.98, 98.01, 3.03),
(3577.35, 3580.01, 2.66),
(3202.63, 3207.82, 5.19),
(1696.04, 1701.94, 5.9),
(1827.46, 1833.33, 5.87),
(395.78, 400.97, 5.19),
(1102.89, 1105.91, 3.02),
(1598.06, 1602.77, 4.71),
(1662.32, 1667.06, 4.74),
(1532.28, 1533.99, 1.71),
(2488.77, 2489.82, 1.05),
(186.59, 190.34, 3.75),
(2875.11, 2879.48, 4.37),
(1796.25, 1801.35, 5.1),
(2989.3, 2994.22, 4.92),
(1084.44, 1085.45, 1.01),
(2668.18, 2669.23, 1.05),
(2632.22, 2636.42, 4.2);
当我执行以下查询时:
select t_received, @chid := floor(t_received / 300) chunk_id, count(*) as number, max(delay) as max_delay
from test
group by chunk_id;
我得到以下结果:
t_已收到 | 块_id | 数字 | 最大延迟 |
---|---|---|---|
98.01 | 0 | 2 | 3.75 |
400.97 | 1 | 1 | 5.19 |
714.61 | 2 | 1 | 1.34 |
1105.91 | 3 | 2 | 3.02 |
1701.94 | 5 | 4 | 5.9 |
1833.33 | 6 | 2 | 5.87 |
2489.82 | 8 | 3 | 4.2 |
2797.09 | 9 | 3 | 5.28 |
3207.82 | 10 | 1 | 5.19 |
3580.01 | 11 | 1 | 2.66 |
问题是,当这些范围内没有记录时,某些 chunk_id 会丢失。我想包含所有可能的 chunk_id(例如,0 到最大 chunk_id),以及那些没有任何记录的 chunk_id。
我希望结果包含计数为 0 的行,如下所示:
t_已收到 | 块_id | 数字 | 最大延迟 |
---|---|---|---|
98.01 | 0 | 2 | 3.75 |
400.97 | 1 | 1 | 5.19 |
714.61 | 2 | 1 | 1.34 |
1105.91 | 3 | 2 | 3.02 |
4 | 0 | 0 | |
1701.94 | 5 | 4 | 5.9 |
1833.33 | 6 | 2 | 5.87 |
7 | 0 | 0 | |
2489.82 | 8 | 3 | 4.2 |
2797.09 | 9 | 3 | 5.28 |
3207.82 | 10 | 1 | 5.19 |
3580.01 | 11 | 1 | 2.66 |
如何在查询中包含缺失的 chunk_ids?
select test.t_received,
t3.chunk_id,
count(*) as number,
max(test.delay) as max_delay
from (
SELECT @chunk_id := @chunk_id + 1 AS chunk_id
FROM (SELECT @chunk_id := FLOOR(MIN(t_received) / 300) - 1
FROM test) t1
JOIN (SELECT FLOOR(MAX(t_received) / 300) AS stop
FROM test) t2
JOIN test
WHERE @chunk_id < t2.stop
) t3
LEFT JOIN test ON t3.chunk_id = floor(test.t_received / 300)
group by chunk_id;
t_已收到 | 块_id | 数字 | 最大延迟 |
---|---|---|---|
98.01 | 0 | 2 | 3.75 |
400.97 | 1 | 1 | 5.19 |
714.61 | 2 | 1 | 1.34 |
1105.91 | 3 | 2 | 3.02 |
空 | 4 | 1 | 空 |
1701.94 | 5 | 4 | 5.9 |
1833.33 | 6 | 2 | 5.87 |
空 | 7 | 1 | 空 |
2489.82 | 8 | 3 | 4.2 |
2797.09 | 9 | 3 | 5.28 |
3207.82 | 10 | 1 | 5.19 |
3580.01 | 11 | 1 | 2.66 |
PS。临时表在查询中不能多次使用,因此使用静态源表。
PPS。自己调整
number
不存在的块。