簡體   English   中英

MYSQL計算收到的消息和第一個答案之間的平均時間

[英]MYSQL calculate average time between messages received and first answer

我有一個mysql表來存儲用戶之間的消息。 我想計算一個特定用戶等待回答他/她從其他用戶收到的第一條消息的平均時間

我的表是這樣的,其中subject_id可以是主題或帖子

|msg_id|sender_id|receiver_id| subject_id |msg           |time               |
--------------------------------------------------------------------------
|   1  |  123    |  456      |     3      |"yadda yadd.."|2016-01-31 00:27:16|
|   2  |  456    |  123      |     3      |"ladida   .." |2016-01-31 00:37:16|
|   3  |  456    |  123      |     3      |"johndo   .." |2016-01-31 01:47:04|
|   4  |  123    |  456      |     3      |"xxxxxx   .." |2016-01-31 02:47:04|
|   5  |  456    |  123      |     3      |"qwerty   .." |2016-01-31 03:47:04|
|   6  |  789    |  456      |     9      |"dadda kadd.."|2016-01-31 00:11:16|
|   7  |  789    |  456      |     9      |"fadda jadd.."|2016-01-31 00:12:16|
|   8  |  456    |  789      |     9      |"fadda jadd.."|2016-01-31 00:13:16|

在該特定情況下,用戶456從用戶123接收消息並在10分鍾后響應。

然后他收到用戶789的消息並在1分鍾內回復。

因此,用戶456的平均響應時間平均為5分鍾。

UPDATE

讓自己更清楚:想一個約會應用程序。 我想計算用戶的平均響應時間是什么,因此其他用戶將知道她/他是快速還是非常慢地回復消息

您可以嘗試以下查詢:

SELECT m1.sender_id, m1.receiver_id,
    AVG(TIMESTAMPDIFF(MINUTE, m1.time, m2.time)) AS DiffInMinutes
FROM messages m1 INNER JOIN messages m2
    ON m1.receiver_id = m2.sender_id AND m1.sender_id = m2.receiver_id AND
        m2.time = (SELECT MIN(time) FROM messages WHERE time > m1.time)
GROUP BY m1.sender_id, m1.receiver_id, m2.sender_id, m2.receiver_id

輸出:

╔═══════════╦═════════════╦═══════════════╗
║ sender_id ║ receiver_id ║ DiffInMinutes ║
╠═══════════╬═════════════╬═══════════════╣
║   123     ║     456     ║      35       ║
║   456     ║     123     ║      60       ║
║   789     ║     456     ║      1        ║
╚═══════════╩═════════════╩═══════════════╝

請點擊以下鏈接查看正在運行的演示:

SQLFiddle

這樣的事情應該有效:

SELECT receiver_id, avg(waiting_time)
FROM (
    SELECT m1.receiver_id , min(TIMESTAMPDIFF(MINUTE, m1.time, m2.time)) as `waiting_time`
    FROM messages m1
    JOIN messages m2
        on m1.receiver_id = m2.sender_id
        and m1.sender_id = m2.receiver_id
        and m1.time < m2.time
    WHERE m1.receiver_id = 456
    GROUP BY m1.sender_id, m1.receiver_id
) as tmp;

結果:

╔═════════════╦═══════════════════╗
║ receiver_id ║ avg(waiting_time) ║
╠═════════════╬═══════════════════╣
║     456     ║      5.5000       ║
╚═════════════╩═══════════════════╝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM