我正在尝试创建聊天应用,并希望启动用户1
和2
的对话。
表:
+----+---------------------+-----------+---------+
| 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 |
+----+---------------------+-----------+---------+
这是我的查询失败:
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)
如何选择用户1
和2
的对话。我的设计对聊天应用程序有效吗?
预期产出:
+----+---------------------+-----------+---------+
| 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可能是必要的
答案 0 :(得分:3)
这应该这样做。
SELECT *
FROM Messages
WHERE (from_user = 1 AND to_user = 2)
OR (from_user = 2 AND to_user = 1);
答案 1 :(得分:2)
单行不能同时拥有to_user=1
和to_user=2
,因此此查询不会返回任何行。相反,您需要使用逻辑or
运算符来区分两个"方向"谈话:
SELECT *
FROM messages
WHERE (from_user = 1 AND to_user = 2) OR (to_user = 1 AND from_user = 2)
答案 2 :(得分:2)
meters