简体   繁体   English

选择列最接近当前日期的MySQL行

[英]Select MySQL row where column is closest to current date

I have a database with a bunch of rows. 我有一个包含大量行的数据库。 One of the columns is "date" which has a date for each row in the format: MM/DD/YYYY H:MM PM/AM 其中一列是“日期”,其格式为每行的日期:MM / DD / YYYY H:MM PM / AM

How can I write PHP that selects the row where the date is the most recent date that has passed. 如何编写PHP选择日期是最近日期的行。 Meaning if you have a date of tomorrow, a date of today, and a date of yesterday, it picks the row where the date is of yesterday. 意思是如果您有明天的日期,今天的日期和昨天的日期,它会选择昨天的日期行。

I've already connected to the database: 我已经连接到数据库了:

mysql_connect('localhost','username','pass');
mysql_select_db('db_name');

How do I write a query to grab this? 如何编写查询以获取此信息?

I would do the filtering in SQL rather than PHP, using a variation of the following query: 我会使用以下查询的变体在SQL而不是PHP中进行过滤:

SELECT *
FROM myTable
WHERE theDate < CURDATE()
ORDER BY theDate DESC
LIMIT 1

This selects all the rows in the past ( theDate < CURDATE() ), sorts them in reverse chronological order ( ORDER BY theDate DESC ), then takes the first record ( LIMIT 1 ). 这将选择过去的所有行( theDate < CURDATE() ),按反向时间顺序( ORDER BY theDate DESC )对它们进行排序,然后获取第一个记录( LIMIT 1 )。

When you query the database, ORDER BY date DESC LIMIT 1 查询数据库时,ORDER BY日期DESC LIMIT 1

This will only return the most recent result, and thus the result that is closest to the current date. 这将仅返回最近的结果,从而返回最接近当前日期的结果。 (This only works if you don't put entries that are dated in the future) (这仅适用于未放置日期的条目)

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

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