如果您有一个日期时间的值,您想要找到 其最近的下一个元素(让我们将其命名为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 替换为 MySQL 函数NOW() 。然后,你可以尝试这样的事情:
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