D
D
Deniev2021-10-11 04:07:25
SQL
Deniev, 2021-10-11 04:07:25

How to get a list of chats by the date the messages were sent?

61638d4961ad0841508774.png

There is a number of users and messages, how to request a list of users with which user 1 has either sent or received messages, so that the list is sorted by sent_at whether they are sent messages or received.

Thanks,

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Akina, 2021-10-11
@deniev

SELECT CASE WHEN sender_id = 1
            THEN receiver_id
            ELSE sender_id 
            END AS buddy
FROM message
WHERE 1 IN (sender_id, receiver_id)
GROUP BY buddy
ORDER BY MAX(sent_at)

Well and accordingly
SELECT user.username
FROM user
JOIN ( SELECT CASE WHEN sender_id = 1
                   THEN receiver_id
                   ELSE sender_id 
                   END AS id,
              MAX(sent_at) sent_at
       FROM message
       WHERE 1 IN (sender_id, receiver_id)
       GROUP BY 1 ) ids USING (id)
ORDER BY ids.sent_at

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question