Mysql查询有效日期计算

时间:2014-05-22 12:09:24

标签: mysql date

我有一张桌子:

ID           RECORD_DATE              
1            2012-12-15 00:00:00      
2            2012-12-16 00:00:00      
3            2012-12-17 00:00:00      
4            2012-12-17 16:00:00      

现在我需要计算相邻日期之间的时间,所以它看起来像:

start                  end                  difference
2012-12-15 00:00:00    2012-12-15 23:59:59  23:59:59
2012-12-16 00:00:00    2012-12-16 23:59:59  23:59:59
2012-12-17 00:00:00    2012-12-17 16:00:00  16:00:00

有没有有效的方法在数据库端进行这种计算?

感谢所有帮助。

4 个答案:

答案 0 :(得分:2)

我不明白你说的是什么,但试试这个

SELECT t1.RECORD_DATE AS start,
       t2.RECORD_DATE AS end,
       TIMEDIFF(t2.RECORD_DATE,t1.RECORD_DATE) AS difference
FROM TABLE AS t1
JOIN TABLE AS t2 ON t1.id = (t2.id + 1);

答案 1 :(得分:0)

使用TIME_DIFF()

使用此类或查询
SELECT
    start,
    end,
    TIMEDIFF(end, start) AS difference
FROM
(
    SELECT 
        t_start.record_date AS start,
        (
            SELECT 
                t_end.record_date
            FROM records AS t_end
            WHERE t_end.id > t_start.id
                    ORDER BY t_end.id
            LIMIT 1
        ) AS end
    FROM records AS t_start
) AS t_boundaries

答案 2 :(得分:0)

这是一种处理相邻行的方法,当它不是顺序时,即在id = 1之后,你可能有4或5等。

select 
t1.RECORD_DATE as `start`,
t2.RECORD_DATE as `end`,
TIMEDIFF(t2.RECORD_DATE, t1.RECORD_DATE) as difference
from table_name t1
join table_name t2 on t2.ID = (
                  select MIN(x.ID) 
                  from table_name x 
                  where x.id > t1.id
)

此外,我注意到您将结束日期从2012-12-16 00:00:00更改为2012-12-15 23:59:59,但不在表中,因此您可能需要使用date_sub()从结尾扣除1秒日期。

答案 3 :(得分:0)

SELECT x.*
     , MIN(y.record_date - INTERVAL 1 SECOND) end
     , TIMEDIFF(MIN(y.record_date) - INTERVAL 1 SECOND,x.record_date) diff 
  FROM my_table x 
  JOIN my_table y 
    ON y.record_date > x.record_date 
 GROUP 
    BY x.id;

如果重要的话,我猜一个OUTER JOIN的技巧可以处理丢失的第二个