简体   繁体   中英

Get time difference between all consecutive rows (latest one not printing)

I'm trying to retrieve all columns data along with the time difference between all consecutive rows from the following table, where (sender_id = 1 OR = 2) and (recipient_id = 2 OR = 1).

CREATE TABLE records (
    id INT(11) AUTO_INCREMENT,
    send_date DATETIME NOT NULL,
    content TEXT NOT NULL,
    sender_id INT(11) NOT NULL,
    recipient_id INT(11) NOT NULL,
    PRIMARY KEY (id)
);

INSERT INTO records (send_date, content, sender_id, recipient_id) VALUES
('2013-08-23 14:50:00', 'record 1/5', 1, 2),
('2013-08-23 14:51:00', 'record 2/5', 2, 1),
('2013-08-23 15:50:00', 'record 3/5', 2, 1),
('2013-08-23 15:50:13', 'record 4/5', 1, 2),
('2013-08-23 16:50:00', 'record 5/5', 1, 2);

Problem is my select query won't output the latest record because of the WHERE clause :

SELECT t1.content, DATE_FORMAT(t1.send_date, '%b, %D, %H:%i') AS 'pprint_date', 
       TIMESTAMPDIFF(MINUTE, t1.send_date, t2.send_date) AS 'duration' 
FROM records t1, records t2 
WHERE (t1.id = t2.id - 1) /*<= this subtraction excludes latest record*/
  AND ((t1.sender_id = 1 AND t1.recipient_id = 2) 
   OR (t1.sender_id = 2 AND t1.recipient_id = 1))
ORDER BY t1.id ASC

How can I properly get the time difference between all consecutive records while still printing all of them ?

I would use a correlated subquery:

select r.*,
       (select r2.send_date
        from records r2
        where (r2.sender_id in (1, 2) or r2.recipient_id in (1, 2)) and
              r2.send_date > r.send_date
        order by r2.send_date asc
        limit 1
       ) as next_send_date
from records r
where r.sender_id in (1, 2) or r.recipient_id in (1, 2);

You can get the duration (instead of the next time) by using TIMESTAMPDIFF(MINUTE, r.send_date, r2.send_date) in the subquery. I think the first version is easier for you to test with to see what is happening.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM