Go Back   CodingForums.com > :: Server side development > MySQL

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 08-28-2008, 02:32 PM   PM User | #1
cancer10
Regular Coder

 
Join Date: Jun 2006
Location: India
Posts: 794
Thanks: 210
Thanked 2 Times in 2 Posts
cancer10 can only hope to improve
Question MySQL: Fetch nearest date

Hey,

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

Code:
select YourDateField from yourTable where yourDateField <= date(now())
Even a search in Google didnt help


Please help.

Thanx
__________________
http://outlineme.com/cancer10
cancer10 is offline   Reply With Quote
Old 08-28-2008, 03:03 PM   PM User | #2
abduraooft
Supreme Master coder!

 
abduraooft's Avatar
 
Join Date: Mar 2007
Location: N/A
Posts: 14,680
Thanks: 158
Thanked 2,182 Times in 2,169 Posts
abduraooft is just really niceabduraooft is just really niceabduraooft is just really niceabduraooft is just really niceabduraooft is just really nice
Try
Code:
select YourDateField from yourTable where yourDateField <= date(now()) order by yourDateField DESC limit 1
__________________
Quote:
The Dream is not what you see in sleep; Dream is the thing which doesn't let you sleep. --(Dr. APJ. Abdul Kalam)
abduraooft is offline   Reply With Quote
Old 08-28-2008, 10:40 PM   PM User | #3
ralph l mayo
Regular Coder

 
ralph l mayo's Avatar
 
Join Date: Nov 2005
Posts: 951
Thanks: 1
Thanked 31 Times in 29 Posts
ralph l mayo is on a distinguished road
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
ralph l mayo is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 06:30 AM.


Advertisement
Log in to turn off these ads.