简体   繁体   English

检索具有最近(之前和之后)给定日期的记录

[英]Retrieving records with the closest (before and after) given date

Consider a tasks table with the given fields : 考虑具有给定字段的tasks表:

id | release_date | task_number
-------------------------------------
1  | 2012-09-01   | task_number#1
2  | 2012-09-07   | task_number#2
3  | 2012-09-11   | task_number#3
4  | 2012-09-05   | task_number#4
5  | 2012-09-21   | task_number#5
6  | 2012-09-31   | task_number#6

I would like to retrieve records closest(before and after) to a given date. 我想检索最近(之前和之后)到给定日期的记录。

I know this can be done by using two separate queries. 我知道这可以通过使用两个单独的查询来完成。

But is there any way to retrieve the closest record in a single mysql query ? 但有没有办法在single mysql query检索最接近的记录?

For example if the given date is 2012-09-11 , the output should be : 例如,如果给定日期是2012-09-11 ,则输出应为:

    id | release_date | task_number
    -------------------------------------
    2  | 2012-09-07   | task_number#2
    3  | 2012-09-11   | task_number#3
    5  | 2012-09-21   | task_number#5

The following should do the trick I think - it uses timeDiff in the order by: 以下应该做我认为的技巧 - 它按顺序使用timeDiff

select 
    id, 
    release_date, 
    task_number 
from 
    tasks 
order by 
    abs(timediff('2012-09-11',release_date)) desc

You could use the value you are entering as a parameter in your connection from PHP like this: 您可以使用您在PHP连接中作为参数输入的值,如下所示:

select 
    id, 
    release_date, 
    task_number 
from 
    tasks 
order by 
    abs(timediff(:yourDate,release_date)) desc

And pass it the string in the same yyyy-mm-dd format quite nicely. 并以相同的yyyy-mm-dd格式将字符串传递给它。

Edit: Interesting comment from chops below, seems spot on accurate - however the following should do the trick as a workaround: 编辑:下面的chops有趣的评论,似乎准确的点 - 但以下应该做的解决方法:

select 
    id, 
    release_date, 
    task_number 
from 
    tasks 
order by 
    abs(time_to_sec(timediff('2012-09-11',release_date))) desc

If you have index on release_date, you can do it like this to earn a better performance. 如果你有release_date的索引,你可以这样做,以获得更好的性能。

select 
    id, 
    release_date, 
    abs( datediff(release_date,"$the_date") ) as sort_key
from tasks
where 
    id = (select id from tasks where release_date > "$the_date" order by created_time limit 1)      
    or 
    id = (select id from tasks where release_date < "$the_date" order by created_time desc limit 1) 
order by sort_key limit 1;

The first subquery will find the id of first date after $the_date, and the second one will find the id of last date before $the_date, after that, we can choose the desire date easily. 第一个子查询将在$ the_date之后找到第一个日期的id,第二个子查询将在$ the_date之前找到最后日期的id,之后,我们可以轻松地选择期望日期。

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

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