I am trying to create a chat app, and I wanted to pull up the conversation of user 1 and 2.
Table:
+----+---------------------+-----------+---------+
| id | message | from_user | to_user |
+----+---------------------+-----------+---------+
| 1 | hello trick | 1 | 2 |
| 2 | hi raf i am okay | 2 | 1 |
| 3 | how is jo doing | 1 | 2 |
| 4 | Hey | 2 | 3 |
| 5 | she is doing well | 2 | 1 |
| 6 | how is kc doing | 2 | 1 |
+----+---------------------+-----------+---------+
This is my failed query:
mysql> SELECT *
-> FROM Messages
-> WHERE from_user = 1
-> AND to_user = 2
-> AND to_user = 1
-> AND from_user = 2;
Empty set (0.00 sec)
How do I achieve selecting conversation of user 1 and 2. Is my design efficient for a chat application?
Expected Output:
+----+---------------------+-----------+---------+
| id | message | from_user | to_user |
+----+---------------------+-----------+---------+
| 1 | hello trick | 1 | 2 |
| 2 | hi raf i am okay | 2 | 1 |
| 3 | how is jo doing | 1 | 2 |
| 5 | she is doing well | 2 | 1 |
| 6 | how is kc doing | 2 | 1 |
+----+---------------------+-----------+---------+
ORDER BY id may be necessary
This should do it.
SELECT *
FROM Messages
WHERE (from_user = 1 AND to_user = 2)
OR (from_user = 2 AND to_user = 1);
mysql> SELECT *
-> FROM Messages
-> WHERE from_user in (1 , 2)
-> AND to_user in (1, 2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With