I need to develop a private messages system between users and here is what I want to do :
I have a table like the following :
id | from_user_id | to_user_id | message
1 | 1 | 2 | Hey n°1 ! <-- Me with user n°2
2 | 2 | 1 | Hey n°2 ! <-- Me with user n°2
4 | 1 | 3 | Hey n°3 ! <-- Me with user n°3
3 | 3 | 2 | Hey n°4 !
We suppose that I'm the user n°1, I want to get a list of my last messages "group by users" and ordered by id, as discussions :
id | with_user_id | message
4 | 3 | Hey n°3 !
2 | 2 | Hey n°2 !
I've tried a request like :
SELECT id, message,
(CASE WHEN from_user_id = 1 THEN to_user_id ELSE from_user_id END) AS with_user_id
FROM privates
WHERE from_user_id = 1 OR to_user_id = 1
GROUP BY with_user_id
ORDER BY id DESC
But I'm getting this :
id | with_user_id | message
4 | 3 | Hey n°3 !
1 | 2 | Hey n°1 !
So the problem is that it selects the first message with user n°1 and not the last.