简体   繁体   English

从数据库获取最近的日期

[英]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. 时间始终是小时的00、15、30或45(这不会有太大的区别),但是正如您所看到的,还有分钟,小时,有时甚至是几天的间隔。

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). 如果有人要求知道2013-09-17 22:52:35的价格,则应退回145.92 (因为直到23:15:01237.89才将价格更改为237.89 )。

I cannot fathom how I can do this using either MySQL or PHP, except perhaps something like this: 我无法理解如何使用MySQL或PHP来做到这一点,除了可能是这样的:

(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". 那将是您的“最近日期”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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