用户 1 和 2 有一个表单。
<form action = "" method = "post">
<input type = "text" name = "msg" placeholder = "message...">
<input type = "submit" name = "submit" value = "send">
</form>
我的数据库中有这张表:
AccID | FROM | TO | MESSAGE
将此消息发送到数据库的 PHP 代码也非常简单:
$sql = "INSERT INTO messages (from, to, message) VALUES ('$userid','$to','$msg')";
$q = mysqli_query($con,$sql);
现在,如果 user1 发送“Hello User 2!”,它将使用 user1 的 id 注册到数据库 from
表,然后将 user2 的 id 注册到 to
> 对吗?如果 user2 发送,则 user2 的 id 将位于 from
中,而 user1 的 id 将位于 to
中。
现在给出这个示例表:(假设其他用户也开始发消息)
AccID | FROM | TO | MESSAGE
1 user1 user2 hello user2!
2 user2 user1 hi watsup?
3 user3 user1 hi user1
4 user4 user3 hey user3
如何仅选择并查看用户 1 和用户 2 的对话?
我尝试了 "SELECT * FROM messages WHERE from,to = 'user1' AND from,to = 'user2'";
但不知为何没有成功。
最佳答案
尝试以下查询。 假设每条记录的 AccID 都是唯一的
,我使用了 ORDER BY AccID
,以便可以按照插入顺序获取消息。
SELECT * FROM messages
WHERE (`from` = 'user1' AND `to` = 'user2') OR (`from` = 'user2' AND `to` = 'user1')
ORDER BY AccID;
另一个选项(为了更好的性能):
SELECT * FROM messages
WHERE `from` IN ('user1','user2') AND `to` IN ('user1','user2')
ORDER BY AccID;
注意: from
和 to
是 SQL 保留关键字。因此,请避免将它们用作表中的列名称。
而是尝试使用一些有意义的名称,这些名称不会与任何保留关键字冲突,并且还可以提高可读性,例如,sent_from_user、sent_to_user。
关于php - 从 PHPDatabase : Message-like Algorithm 选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44752176/