如果您有日期時間要找到其最接近的下一個元素的值(我們將其命名爲comparison_date),你可以嘗試這樣的事:
SELECT * FROM table_name WHERE column_name IN (SELECT MIN(column_name) FROM table_name WHERE column_name > comparison_date ORDER BY column_name)
這將返回所有日期時間值晚於該日期。如果你想將其限制在一個結果,你應該使用:
SELECT * FROM table_name WHERE column_name IN (SELECT MIN(column_name) FROM table_name WHERE column_name > comparison_date ORDER BY column_name) LIMIT 1
另外,如果你想從當前時間的下一個最接近的日期時間,你可以用替代comparison_date NOW()這是一個MySQL功能。然後,你可以嘗試這樣的事:
SELECT * FROM table_name WHERE column_name IN (SELECT MIN(column_name) FROM table_name WHERE column_name > NOW() ORDER BY column_name)
爲了尋找下一個更低的日期時間(或之前的日期時間,但是我們把它),你應該使用:
SELECT * FROM table_name WHERE column_name IN (SELECT MIN(column_name) FROM table_name WHERE column_name < comparison_date ORDER BY column_name DESC) LIMIT 1