So I am trying to build a chat system and am currently trying to list the conversations of a user.
This is my sql table:
ID | FROM_USER | TO_USER | MESSAGE ------------------------------------------------------------ 1 | 16 | 29 | Hey! 2 | 29 | 18 | Hii.. 3 | 29 | 16 | What's up?
What I’m trying to do is that show the users whom the user 29 (current user) has texted and the users who have messaged 29. How to achieve this? I have tried it using the ‘GROUP BY’ statement and the ‘DISTINCT’ statement but nothing seems to work. How do I achieve this?
Advertisement
Answer
show the users whom the user 29 (current user) has texted and the users who have messaged 29
You can list all users that received messages from user 19 or sent messages to him as follows:
SELECT DISTINCT CASE WHEN from_user = 19 THEN to_user ELSE from_user END as other_user FROM mytable WHERE from_user = 19 OR to_user = 19