I\'m trying to figure out how to write a MySQL query that will return the closest 3 events in terms of date.
This is my table:
EVENT_ID EVENT_NAME
The query from accepted answer actually just sort previously selected values, not filter them before select. But this query works for me:
SELECT event_id, event_date
FROM events
WHERE ABS(TIMESTAMPDIFF(DAY, event_date, $some_date)) < 10
ORDER BY event_date
Explanation: number 10 is a day range (both after and before). Without ABS()
you can select only previous or future events, but I needed the closest.
SELECT event_id
FROM Table
ORDER BY ABS( DATEDIFF( EVENT_START_DATE, NOW() ) )
LIMIT 3
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
SELECT *
FROM table
WHERE EVENT_START_DATE >= NOW()
ORDER BY EVENT_START_DATE
LIMIT 3
I suppose this is what you'd be looking for. It's similar to everyone elses responses aswell.
SELECT EVENT_ID FROM TABLE WHERE EVENT_START_DATE > NOW() ORDER BY ABS(DATEDIFF(EVENT_START_DATE, NOW())) ASC LIMIT 3
SELECT event_id FROM Table ORDER BY EVENT_START_DATE LIMIT 3