I have this table:
| msg_id | msg | from_user | to_user |
|---|---|---|---|
| 1 | Hello! | 16 | 77 |
| 2 | Wassup? | 16 | 77 |
| 3 | Hey there! | 77 | 16 |
| 4 | Hola! | 7 | 77 |
I want to group these messages in descending order while taking 77 as current user, like this:
| msg_id | msg | other_user |
|---|---|---|
| 4 | Hola! | 7 |
| 3 | Hey there! | 16 |
This is what I have tried:
SELECT (CASE WHEN from_user = 77 THEN to_user ELSE from_user END) AS other_user,
MAX(msg_id) as id,
msg
FROM chat_schema
WHERE 77 IN (from_user, to_user)
GROUP BY other_user
ORDER BY id DESC;
This is the result of following query:
| id | msg | other_user |
|---|---|---|
| 4 | Hola! | 7 |
| 3 | Hello! | 16 |
For some reason, the ids are correct but the message does not match up with that id (id 3 message is 'Hey there' but it's returning 'Hello!' which is id 1). It is fetching the first message of each group instead of the message from that particular id. How to fix this?