php - mysql php私有(private)消息系统重复行

标签 php mysql

大家好,我在 mysql 中遇到问题,我必须使用相同的变量 (3) 对两个 user1 和 user2 字段进行搜索,并且我不会复制这两个字段

表名 pm:

id    user1    user2    message    timestamp    user1read    user2read
1       3        4     edfdfdfdf      1            yes          no
2       3        5     ererererer     1            yes          no
3       5        3     gfffgfgdfdfd   1            yes          no
4       6        3     ewwwewewe      1            yes          no
5       7        3    ewwwewddfdfewe  1            yes          no
6       3        7    ewwwewddffewe   1            yes          no

我试过了

$q= mysqli_query("SELECT DISTINCT user1,user2 FROM pm WHERE (user1='3') or (user2='3') ") or die(mysql_error());

他打印:

user1 user2
3      4
3      5
5      3
6      3
7      3
3      7

我要打印

user1 user2
3      4
3      5
6      3
7      3

最佳答案

请尝试此查询。

SELECT user1,user2
FROM pm T1 
INNER JOIN 
  (SELECT MIN(id) as min_id,
         LEAST(user1,user2) as id1,
         GREATEST(user1,user2) as id2
  FROM pm
  WHERE user1 = 3
  OR user2 = 3
  GROUP BY id1,id2)T2
ON T1.id = T2.min_id
ORDER BY T1.id ASC

http://sqlfiddle.com/#!9/8fd88/1

该查询的作用是通过子查询找到用户 ID 3 与其他人的对话的最小 ID(按较小的用户 ID 和较大的用户 ID 分组)。然后它与 pm 表连接回来,获取这些最小 id 的 user1 和 user2 id。

您要查找的本质上是用户 ID 3 与其他人之间第一条消息的用户 ID。

关于php - mysql php私有(private)消息系统重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36879055/

相关文章:

mysql - "longest film rental duration and the customer who rented the said film"MySQL Sakila 查询

mysql - 为 sql 表中的重复项设置标志

PHP,在json中索引mysql ID。这值得么?

php - 更新 MySQLI 中的参数

PHP PDF生成问题

php - MySQL查询按列排名

PHP 复选框验证

php - 将 PayPal IPN 与 PHP 集成 - cURL 错误 : SSL CA cert

mysql - 从数据库读取最新行的最佳实践

MySQL 索引 |与 LIKE 一起使用