问题
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