开发者

MYSQL pick date from available date ranges closest to current date

I've a question regarding MYSQL queries, and how I could go about handling getting the closest date range to the current date...

So I have records in the form of id, from_date, until_date.

Given the current date, I would like to select the record that not only includes the current date, but if there is more than one record which meets the requirement, that the one which has its from and until dates closest to the current date, such that for example:

if:

record1: from_date1, until_date1
record2: from_date2, until_date2

from_date1 <= current_date <= until_date1
from_date2 <= current_date <= until_date2

from_date1 >= from_date2 and until_date1 <= until_date2

record1 should be chosen...

I am looking for a select query syntax to achieve this...

I hope I am being clear enough in my 开发者_运维技巧example... any help would be greatly appreciated!

Thanks! :)

Piotr.


SELECT from_date, until_date
    FROM table
    WHERE current_date BETWEEN from_date
        AND until_date
    ORDER BY TIMESTAMPDIFF(SECOND, from_date, until_date)
    LIMIT 1

selects all records who match the condition; the last one is not obeyed to 100% - what if from_date2 is very close to current_date, but until_date2 so far away that the time span is larger?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜