Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do multiple encapsulated WHERE clauses

Tags:

sql

select

mysql

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

like image 812
edmamerto Avatar asked Jan 19 '26 18:01

edmamerto


2 Answers

This should do it.

SELECT *
    FROM Messages
    WHERE (from_user = 1 AND to_user = 2)
       OR (from_user = 2 AND to_user = 1);
like image 123
Joe Stefanelli Avatar answered Jan 21 '26 08:01

Joe Stefanelli


mysql> SELECT *
-> FROM Messages
-> WHERE from_user in (1 , 2)
-> AND to_user in (1, 2);
like image 44
Anthony Horne Avatar answered Jan 21 '26 08:01

Anthony Horne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!