计算数据库的时差

时间:2014-05-26 15:59:38

标签: php mysql

我有一张表hsave_work_duration

`id_login`   `id_agent`   `agent_name`   `sys_time`              `status`

28               2         hsaveadmin     2014-05-26 12:13:12     Login

28               2         hsaveadmin     2014-05-26 12:19:12     Logout

我想计算用户登录和注销之间的时差?

1 个答案:

答案 0 :(得分:0)

您可以使用同一个表格中的INNER JOINTIMESTAMPDIFF功能结合使用。

SELECT TIMESTAMPDIFF(MINUTE,s1.sys_time,s2.sys_time) AS timediff
FROM hsave_work_duration AS s1
INNER JOIN hsave_work_duration AS s2
ON 
    s1.id_login = s2.id_login AND
    s1.id_agent = s2.id_agent
WHERE agent_name = 'hsaveadmin';

如果您有超过这两个状​​态,请将以下内容添加到WHERE子句中:

AND s1.status = 'Login'
AND s2.status = 'Logout'

如果您希望timediff不在几分钟内查看this section in the MySQL Reference并更改TIMESTAMPDIFF函数中的第一个参数。

这可以用PHP执行(即使用mysqli连接器):

$mysqli = new mysqli("localhost", "user", "password", "database");
$query = <the sql stmt>;
if ($result = $mysqli->query($query)) {
    $row = $result->fetch_assoc();
    print($row["timediff"]);
}

有关SQL的更多信息,请查看:http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampdiff