MySQL中的下一个最接近的日期和时间

时间:2012-10-11 05:48:13

标签: mysql

在我的Auctions表格中,我有一个名为Auction_StartDate的列。行的值如下所示:2012-10-27 13:45:30

我需要一个返回下一个最接近的日期和时间的查询。因此,如果下一个Auction_StartDate为2012-10-27 18:30:00,则应在日期转为2012-10-28之前返回。

4 个答案:

答案 0 :(得分:1)

您可以使用MIN查找最接近的值,而不使用LIMIT and ORDER BY子句。

SELECT  MIN(DATE(Auction_StartDate)) closestDate
FROM    Auctions
WHERE   DATE(Auction_StartDate) > '2012-10-27'

SQLfiddle Demo

答案 1 :(得分:1)

如果您想为每一行执行此操作,请尝试以下操作:

SELECT a1.id,
    (SELECT MIN(a2.Auction_StartDate) 
     FROM Auctions a2 
     WHERE a2.Auction_StartDate > a1.Auction_StartDate) AS nextStartDate
FROM Auctions a1

答案 2 :(得分:0)

可能是这个帮助

    SELECT DATE(Auction_StartDate) closestDate
    FROM    Auctions
    WHERE   DATE(Auction_StartDate) > '2012-10-27'
    order by Auction_StartDate ASC
    limit 1

答案 3 :(得分:0)

   SELECT (case when Hour(StartDate)>=12 then DATE_ADD(StartDate,
                  INTERVAL 1 DAY) else StartDate end) as 'date' FROM table  
    ------------------------------
    pleaes add your column name where is static date : 
    est on : http://sqlfiddle.com/#!2/b8435/19

    SELECT (case when Hour(StartDate )>=12 then 
       DATE_FORMAT( DATE_ADD(StartDate ,INTERVAL 1 DAY), '%Y-%m-%d')                
       else DATE_FORMAT(StartDate , '%Y-%m-%d') end) as 'date'  from tabel