time difference between two rows - mysql

ぃ、小莉子 提交于 2021-02-08 12:14:28

问题


I wanted to know if there is any way where i can calculate time difference between two rows. I want to calculate time difference for name -> test etc. The name can be in any order.

I want to know if test has two times at row 1 and 3 and then at row 7 and 11, can i calculate time difference between these rows? i.e for row 1 and 3, and other for row 7 and 11.

below image with my database


回答1:


try using TIMEDIFF() and subquery

SELECT TIMEDIFF((SELECT `entered_at` FROM `demo_test3` WHERE `id`='1'),
               (SELECT `entered_at` FROM `demo_test3` WHERE `id`='3'))



回答2:


If you want to check the difference in PHP you can do something like this.

function secondsBetweenRows($first, $second)
{
    return strtotime($second->entered_at) - strtotime($first->entered_at);
}

// group rows by users
$users = []
foreach ($rows as $row) {
    $users[$row->name] = $row;
}

// check row difference
$timeDiff = [];
foreach ($users as $userName => $userRows) {
    // assume there are always to, if not do some checks here
    $timeDiff[$userName] = secondsBetweenRows($userRows[1], $userRows[0]);
}

print_r($timeDiff);
/*
  Array
  (
      [test]  => 24
      [test1] => 26
  )
*/


来源:https://stackoverflow.com/questions/43276257/time-difference-between-two-rows-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!