简体   繁体   中英

Getting nearest date from database

I have a database filled with data in the following format:

DateTime*             Price
2013-09-17 22:15:01   13.45
2013-09-17 22:30:02   145.92
2013-09-17 23:15:01   237.89
2014-09-17 03:15:02   95.01
2014-09-21 12:45:02   108.32
...                   ...

It goes on for years. Times are always 00, 15, 30 or 45 past the hour (not that should make much difference), but as you can see, there are gaps of minutes, hours, and sometimes days.

If someone requests to know what the price was at 2013-09-17 22:52:35 , they should be returned 145.92 (because the price didn't change to 237.89 until 23:15:01 later that day).

I cannot fathom how I can do this using either MySQL or PHP, except perhaps something like this:

(pseudo code)

CONVERT TIME SO DATETIME MINUTES END IN 00, 15, 30 or 45
SEARCH DATABASE FOR THAT EXACT DATETIME
WHILE DATETIME NOT FOUND IN DB {
    CHECK DATABASE FOR DATETIME -15 MINUTES
}

It seems very inefficient. Is there a better way?

It's pretty simple:

SELECT *
FROM yourtable
WHERE datetime <= 'the date user is looking for'
ORDER BY datetime DESC
LIMIT 1

get all the records from BEFORE the user's specified date, sort them in descending order, then return only the first record. That'll be your "most recent date before".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM