2017-10-16 20 views
0

我試圖從下表中檢索所有列數據以及所有連續行之間的時間差,其中(sender_id = 1 OR = 2)和( 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); 

問題是我的選擇查詢,不會因爲輸出的最新記錄WHERE子句:

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 

我怎樣才能正確地獲得所有連續記錄之間的時間差,同時還打印所有的人?

+0

編輯您的問題並提供預期結果。 –

回答

1

我會用一個相關子查詢:

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); 

您可以通過使用子查詢得到TIMESTAMPDIFF(MINUTE, r.send_date, r2.send_date)的持續時間(而不是下一次)。我認爲第一個版本更容易測試,看看發生了什麼。

+0

您的查詢完美無缺,我只需在where子句中添加括號以防止「next_send_date」始終是第一個記錄日期。謝謝 ! –

相關問題