-3

我在数据库中有一个临时表,其中包含:

 userid | time              
--------|---------------------
 1      | 13-01-24 00:04:01 
 1      | 13-01-24 00:04:04 
 1      | 13-01-24 00:05:06 
 2      | 13-01-24 00:06:06 
 2      | 13-01-24 00:06:08 

我想得到如下答案:

1,  0 second
1,  3 second
1,  62 second
2,  60 second
2,  2 second

我试过'TIMEDIFF'脚本(max(time), min(time)),但它没有输出我想要的。请帮忙,我正在使用PHP。

4

2 回答 2

1

MySQL解决方案:

SET @prev_time = null;
SELECT userid, IFNULL(timediff(`time`,@prev_time), 0) diff,
       @prev_time := `time`
FROM mytable
ORDER BY time

SQLFIDDLE

于 2013-06-01T00:00:00.730 回答
0

PHP解决方案:

(相同的@Barmar 的解决方案,但在 php 中)

<?php
$timearray = array("13-01-24 00:04:01", "13-01-24 00:04:04", "13-01-24 00:05:06", "13-01-24 00:06:06", "13-01-24 00:06:08");
$prevtimestamp = null;
foreach($timearray as $it) {
    $datetime = explode(" ", $it);
    $date = explode("-", $datetime[0]);
    $time = explode(":", $datetime[1]);
    $newtimestamp = mktime($time[0], $time[1], $time[2], $date[1], $date[0], $date[2]);
    if($prevtimestamp == null) $prevtimestamp = $newtimestamp;
    echo $newtimestamp - $prevtimestamp . " seconds";
    $prevtimestamp = $newtimestamp;
}
?>
于 2013-06-01T00:05:52.133 回答