以 24 小时为周期,当前时间等于或小于 MySQL

Current time equal or less than in MySQL at 24 hour cycle

以 24 小时为周期搜索小于当前时间的最佳方法是什么?

数据库

+----+----------+-----------+
| id | time     | name      |
+----+----------+-----------+
|  1 | 07:00:00 | Breakfast |
|  2 | 12:00:00 | Lunch     |
|  3 | 18:00:00 | Dinner    |
|  4 | 21:00:00 | Supper    |
+----+----------+-----------+

我的解决方案

当前时间为15:00:00

SELECT * FROM schedules where time < CURRENT_TIME() ORDER BY time DESC LIMIT 1
+----+----------+-------+
| id | time     | name  |
+----+----------+-------+
|  2 | 12:00:00 | Lunch |
+----+----------+-------+

但我的解决方案在 02:00:00

下不起作用
+----+----------+-------+
| id | time     | name  |
+----+----------+-------+
+----+----------+-------+

如何搜索02:00:00,结果是:

+----+----------+--------+
| id | time     | name   |
+----+----------+--------+
|  4 | 21:00:00 | Supper |
+----+----------+--------+

您可以使用 union all:

强制在结果中包含最后一行
(
    -- when current time is gte 07:00
    select *
    from schedules
    where time <= current_time()
    order by time desc
    limit 1
)
union all
(
    -- union last row if no matching row exists for previous query
    select *
    from schedules
    where not exists (
        select *
        from schedules
        where time <= current_time()
    )
    order by time desc
    limit 1
)