php - 从 PHPDatabase : Message-like Algorithm 选择数据

标签 php mysql

用户 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;

注意: fromto 是 SQL 保留关键字。因此,请避免将它们用作表中的列名称。
而是尝试使用一些有意义的名称,这些名称不会与任何保留关键字冲突,并且还可以提高可读性,例如,sent_from_user、sent_to_user。

关于php - 从 PHPDatabase : Message-like Algorithm 选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44752176/

相关文章:

php - MYSQLI准备语句bind_param类型不起作用

php - 使用 PHP 显示网页今天、月份和年份的 View ,无需添加到数据库

php - WooCommerce get_availability() 返回一个数组

mysql - 嵌套 select 语句 mysql 中的 IFNULL

MySQL 可以远程连接但不能本地连接

php - 选择多个用户并向他们发送邀请

PHP 结构 - 接口(interface)和 stdClass 变量

javascript - 根据mysql日期格式格式化日期

mysql - 两个表,有索引,有相同的列名,包含不同的信息......会发生冲突吗?

c# - 从多个文本框中选择查询c#