计算与日期时间上一行的天差

时间:2019-01-17 13:49:57

标签: mysql datediff

我有一个用Created_at作为datetime列创建的log_file表,我需要通过created_at在行之间获取天数

select id,DATE(created_at), datediff( created_at, prev_date) as diff
from (select t.*,
         (select DATE(t2.created_at)
          from log_file t2
          where t2.id = t.id and
                DATE(t2.created_at) <  DATE(t.created_at)
          order by  t2.created_at desc
          limit 1
         ) as prev_date
  from log_file t
 )  t

但是它在diff中给了我空值

    id DATE(created_at) diff
     2 2019-01-16       NULL
     3 2019-01-19       NULL
     4 2019-01-21       NULL

1 个答案:

答案 0 :(得分:2)

如果您使用的MySQL版本早于8+,并且您也不想使用会话变量,那么使用相关子查询是此处的一种方法。

SELECT
    t1.id,
    t1.created_at,
    DATEDIFF(t1.created_at,
             (SELECT t2.created_at FROM log_file t2
              WHERE t2.created_at < t1.created_at
              ORDER BY t2.created_at DESC LIMIT 1)) AS diff
FROM log_file t1;

您处在正确的轨道上,但是子查询中的WHERE子句的添加条件不正确:

where t2.id = t.id

删除它,您当前的代码甚至可以按原样工作。