我有一个查询,可以在给定的15分钟时间间隔内产生正确的结果。
-- Query for the interval 10:00-10:15
SELECT count(r.id) as nof_reservations_in_interval
FROM reservations r
LEFT JOIN assets a ON r.asset_id = a.id
WHERE r.deleted_at is null
AND a.type_id = 23 --just an ID
AND r.start_utc <= '2017-02-21 10:15:00'
AND r.end_utc >= '2017-02-21 10:00:00'
-- result: 2
如果我想在同一天的10:00和18:00之间与此查询的结果建立“表/关系”。我怎么能实现这一目标?
我可以在每个时间间隔从php查询语句;但是我希望有一些聪明的MySQL函数可以做到这一点:)
期望的结果关系:
interval_start | interval_end | nof_reservations_in_interval
---------------+--------------+------------------------------
10:00 | 10:15 | 2
10:15 | 10:30 | 3
etc etc
答案 0 :(得分:1)
一种简单的方法是使用子查询定义间隔:
SELECT t.time_start, t.time_end, count(r.id) as nof_reservations_in_interval
FROM (SELECT time('10:10:00') as time_start, time('10:15:00') as time_end UNION ALL
SELECT time('10:15:00') as time_start, time('10:30:00') as time_end
) t LEFT JOIN
reservations r
ON r.start_utc <= addtime('2017-02-21', t.time_end) AND
r.end_utc >= addtime('2017-02-21', t.time_start) LEFT JOIN
assets a
ON r.asset_id = a.id AND
a.type_id = 23
WHERE r.deleted_at is null
GROUP BY t.time_start, t.time_end;
注意:我已将a.type_id
上的条件移至on
条款,以使left join
生效。