I have a mysql table to store messages between users. I'd like to calculate the average time a specific user waits to answer to the first message he/she receives from other users
my table is something like this, where subject_id could be the thread or post
|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|
In this specific case the user 456, received a message from user 123 and responded 10 mins later.
Then he received a message from user 789 and responded in 1 minute.
So the average response time for user 456 is say 5 minutes on average.
UPDATE
to make myself more clear: think a dating app. i want to calculate what's the average response time of a user, so other user will know if she/he is quick or very slow answering messages
答案 0 :(得分:2)
Here is a query you can try:
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
Output:
╔═══════════╦═════════════╦═══════════════╗
║ sender_id ║ receiver_id ║ DiffInMinutes ║
╠═══════════╬═════════════╬═══════════════╣
║ 123 ║ 456 ║ 35 ║
║ 456 ║ 123 ║ 60 ║
║ 789 ║ 456 ║ 1 ║
╚═══════════╩═════════════╩═══════════════╝
Follow the link below for a running demo:
答案 1 :(得分:2)
Something like this should work :
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;
Result :
╔═════════════╦═══════════════════╗
║ receiver_id ║ avg(waiting_time) ║
╠═════════════╬═══════════════════╣
║ 456 ║ 5.5000 ║
╚═════════════╩═══════════════════╝