Question

my question is:

assuming we have a calendar_table with UNIX datestamp date_column, i want retrieve the event with the closest proximity to the today date.

So, for example if there is no event today, keep the closest one based on it's date!

UPDATED

probably i need to be more clear, i need to retrieve not just one event, but All events in the table with the same date, closest to today date!

Thanks All you guys! ;-)

Was it helpful?

Solution

SELECT * FROM `calendar_table` WHERE `date_column` = (SELECT `date_column` FROM `calendar_table` ORDER BY ABS(`date_column` - UNIX_TIMESTAMP()) ASC LIMIT 1)

OTHER TIPS

SELECT *
FROM `calendar_table`
ORDER BY ABS(`date_column` - UNIX_TIMESTAMP()) DESC
LIMIT 1

What you can do is make select the difference between today's date and the event date, and select the smallest result.

First select the difference like this:
SELECT DATEDIFF(EventDate, Now()) As Datediff FROM calendar
or if you want to find events in the past as well:
SELECT Abs(DATEDIFF(EventDate, Now())) As Datediff FROM calendar

Then just order by that field and take the first one off the list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top