Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query to show nearest date?

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     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 

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..

EDIT: query should find only future events.

like image 765
Or Weinberger Avatar asked May 31 '11 11:05

Or Weinberger


People also ask

How do I find the nearest date in SQL?

The where clause will match all rows with date less than @CurrentDate and, since they are ordered descendantly, the TOP 1 will be the closest date to the current date. Depends on the database design.

What does date () do in SQL?

Date Function DAY() The date function DAY accepts a date, datetime, or valid date string and returns the Day part as an integer value.


2 Answers

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  
like image 186
Mat Avatar answered Sep 21 '22 21:09

Mat


  SELECT *     FROM table    WHERE EVENT_START_DATE >= NOW() ORDER BY EVENT_START_DATE    LIMIT 3 
like image 41
hsz Avatar answered Sep 20 '22 21:09

hsz