CREATE TABLE log (
id INT NOT NULL AUTO_INCREMENT,
dt DATETIME NOT NULL,
status VARCHAR(255),
PRIMARY KEY (id)
);
INSERT INTO log VALUES
(1, '2018-07-10 12:01:00' ,'keyout'),
(2, '2018-07-10 12:02:00' ,'keyout'),
(3, '2018-07-10 12:03:00' ,'keyinside'),
(4, '2018-07-10 12:44:00' ,'keyout'),
(5, '2018-07-10 13:02:00' ,'keyinside');
SELECT MIN(dt) dto
, dti
, SEC_TO_TIME(TIME_TO_SEC(dti)-TIME_TO_SEC(MIN(dt))) diff
FROM
( SELECT x.dt
, MIN(y.dt) dti
FROM log x
JOIN log y ON y.dt > x.dt
AND y.status = 'keyinside'
WHERE x.status = 'keyout'
GROUP
BY x.dt
) a
GROUP
BY dti;
+---------------------+---------------------+----------+
| dto | dti | diff |
+---------------------+---------------------+----------+
| 2018-07-10 12:01:00 | 2018-07-10 12:03:00 | 00:02:00 |
| 2018-07-10 12:44:00 | 2018-07-10 13:02:00 | 00:18:00 |
+---------------------+---------------------+----------+