我有一张 table 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
我想计算用户登录和注销之间的时间差?
最佳答案
您可以在同一个表上使用 INNER JOIN
结合 TIMESTAMPDIFF
函数来完成此操作。
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'
如果您想要时间差而不是分钟,请查看 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
关于php - 计算与数据库的时间差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23873907/