mysql从今天开始选择最接近的日期

时间:2017-01-02 18:01:27

标签: mysql sql

我有下表

    date
-----------------------
1. 2017-01-02 20:59:00
2. 2017-01-04 10:00:00
3. 2017-01-04 11:00:00
4. 2017-01-09 17:20:00

Q1:假设今天是2017-01-03,我如何选择上述日期才能获得2和3的结果?

Q2:假设今天是2017-01-05,得到4的结果?

4 个答案:

答案 0 :(得分:1)

试试这个:

select `date`
from your_table
where date(`date`) = (select min(date(`date`))
    from your_table
    where date(`date`) > date(now())
);

答案 1 :(得分:0)

试试这个:

SELECT *
FROM Table 
WHERE datecol > NOW() 
AND datecol < CURDATE() + INTERVAL 1 DAY
LIMIT 1

答案 2 :(得分:0)

Q1答案:

SELECT
    *
FROM
    closest_date_table
WHERE
    date(`date`) = (
        SELECT
            min(date(`date`))
        FROM
            closest_date_table
        WHERE
            date(`date`) > date('2017-01-03')
    );

Q2答案:

SELECT
    *
FROM
    closest_date_table
WHERE
    date(`date`) = (
        SELECT
            min(date(`date`))
        FROM
            closest_date_table
        WHERE
            date(`date`) > date('2017-01-05')
    );

LIVE SQL FIDDLE DEMO

答案 3 :(得分:-1)

试试这个,

select top 1 * from tblDate where date >GETDATE()  order by date asc