我想弄清楚如何编写一个 MySQL 查询,该查询将返回最接近日期的 3 个事件.
I'm trying to figure out how to write a MySQL query that will return the closest 3 events in terms of date.
这是我的桌子:
EVENT_ID EVENT_NAME EVENT_START_DATE(DATETIME)
1 test 2011-06-01 23:00:00
2 test2 2011-06-03 23:00:00
3 test3 2011-07-01 23:00:00
4 test4 2011-08-09 23:00:00
5 test5 2011-06-02 23:00:00
6 test6 2011-04-20 23:00:00
因此查询结果应该是 ID 的 1,2,5,因为它们与当前日期相比最接近发生..
So the query result should be for ID's 1,2,5 as they are the closest to occur in comparison to the current date..
查询应该只找到未来的事件.
query should find only future events.
SELECT event_id
FROM Table
ORDER BY ABS( DATEDIFF( EVENT_START_DATE, NOW() ) )
LIMIT 3
ABS()
表示 1 天前的事件与未来 1 天的事件一样接近.如果您只想要尚未发生的事件,请执行
The ABS()
means that an event 1 day ago is just as close as an event 1 day in the future. If you only want events that haven't happened yet, do
SELECT event_id
FROM Table
WHERE EVENT_START_DATE > NOW()
ORDER BY EVENT_START_DATE
LIMIT 3
这篇关于SQL查询显示最近的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!