以 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 |
---- ---------- --------
uj5u.com熱心網友回復:
您可以使用以下命令強制在結果中包含最后一行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
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/453095.html
上一篇:計算最后一行中每一列的平均值
