Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
Thread: MySQL: Fetch nearest date
08-28-2008, 02:32 PM #1
- Join Date
- Jun 2006
- Thanked 2 Times in 2 Posts
MySQL: Fetch nearest date
How do I get the nearest date/time row populated using sql?
The datatype for this date field is "datetime"
I tried the folowing, but does not work properly
select YourDateField from yourTable where yourDateField <= date(now())
08-28-2008, 03:03 PM #2
- Join Date
- Mar 2007
- Thanked 2,223 Times in 2,210 Posts
- Blog Entries
TryCode:select YourDateField from yourTable where yourDateField <= date(now())
order by yourDateField DESC limit 1
The Dream is not what you see in sleep; Dream is the thing which doesn't let you sleep. --(Dr. APJ. Abdul Kalam)
08-28-2008, 10:40 PM #3
The previous example returns the closest date to now() that is before or equal to now(), even if there is a closer date after now(). If you want the absolute closest date try something like:
Code:SELECT date FROM table ORDER BY abs(now() - date) LIMIT 1
Last edited by ralph l mayo; 08-29-2008 at 07:17 AM. Reason: typo