不同行的时间差异mysql

时间:2017-10-31 22:44:01

标签: mysql sql database

我正在尝试编写mysql查询,它可以组合同一个表的两行并找到时间戳的差异

我有这张桌子

CREATE TABLE `facebook` (
  `logid` int(15) NOT NULL AUTO_INCREMENT,
  `times` double DEFAULT '0',
  `userid` varchar(255) DEFAULT '',
  `statusoflogin` varchar(255) DEFAULT '',
  `Game` varchar(255) DEFAULT '',
  PRIMARY KEY (`logid`),
  UNIQUE KEY `times` (`times`,`userid`)
)

logid |次| userid | statusoflogin |游戏|

01 | 12:30:23 | GT |在|

02 | 12:45:23 | GT |出|

03 | 01:45:23 | RT |在|

04 | 01:50:23 | GT |在|

05 | 01:55:23 | RT |出|

06 | 02:05:23 | RT |在|

07 | 02:10:23 | GT |出|

08 | 02:40:23 | RT |出|
_------------------------------------------------- ------

,结果必须是

| times.login | times.logout | userid |持续时间

| 12:30:23 | 12:45:23 | GT | 15个
| 01:45:23 | 01:55:23 | RT | 10个
| 01:50:23 | 02:10:23 | GT | 20个
| 02:05:23 | 02:40:23 | RT | 35

_----------------------------------------

我使用了这段代码,但没有给我所需的结果

 SELECT
    fIn.userid,
    fIn.times AS in_time,
    fOut.times AS out_time,
  TIMEDIFF (fOut.times,fIn.times) AS Duration
FROM
    facebook AS fIn
 JOIN
    facebook AS fOut ON (
            fIn.userid = fOut.userid
        AND
            fOut.times > fIn.times)
WHERE fIn.statusoflogin = 'in'
AND fOut.statusoflogin = 'out'
GROUP BY fIn.userid;

1 个答案:

答案 0 :(得分:0)

您正在聚合。你需要聚合:

SELECT fIn.userid, fIn.times as in_time,
       MIN(fOut.times) as out_time,
       TIMEDIFF(MIN(fOut.times), fIn.times) as Duration
FROM facebook fIn JOIN
     facebook fOut
     ON fIn.userid = fOut.userid AND
        fOut.times > fIn.times)
WHERE fIn.statusoflogin = 'in' AND fOut.statusoflogin = 'out'
GROUP BY fIn.userid, fIn.times;