Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 输出mysql独特查询只输出我想要的信息_Php_Mysql - Fatal编程技术网

Php 输出mysql独特查询只输出我想要的信息

Php 输出mysql独特查询只输出我想要的信息,php,mysql,Php,Mysql,我想创建一个聊天/下午系统,我有一个特定的查询,我想做一些麻烦排序 我有一个名为messages的表,其中包含以下字段 ID,从用户ID到用户ID,内容 当进入收件箱时,我想显示我与之通信但唯一的所有用户。例如,我的数据库中有以下内容 ID, From_user_id, To_user_id, Content 1, 1, 2, hi 2, 1, 2, hello 3, 2, 1,

我想创建一个聊天/下午系统,我有一个特定的查询,我想做一些麻烦排序

我有一个名为messages的表,其中包含以下字段

ID,从用户ID到用户ID,内容

当进入收件箱时,我想显示我与之通信但唯一的所有用户。例如,我的数据库中有以下内容

ID, From_user_id, To_user_id, Content
1,  1,            2,          hi
2,  1,            2,          hello
3,  2,            1,          hi
4,  1,            3,          hi
5,  3,            1,          hi
在user1的收件箱中,我想回显user_id 2和user_id 3 在user2的收件箱中,我想回显用户id 1 在user3的收件箱中,我想回显用户id 1

我尝试了以下代码

$qinbox = "SELECT DISTINCT from_users_id, to_users_id from messages
WHERE from_users_id = $id OR to_users_id = $id";

$queryinbox = $db->query($qinbox);

while ($inbox = $queryinbox->fetch(PDO::FETCH_ASSOC)) {
            echo $inbox['from_users_id']; 
            echo $inbox['to_users_id']; echo ' <p>' ; }
而我希望结果是独一无二的。不管是谁。所以从或到都无关紧要


比如facebook或linkedin聊天。因此,如果我在这个实例中是user1,我只想看到user2和user3一次

我想像这样的东西应该可以

SELECT DISTINCT a.user_id
FROM (SELECT from_users_id as user_id 
      FROM messages WHERE to_users_id = $id 
      UNION SELECT to_users_id 
      FROM messages WHERE from_users_id = $id) as a

没有联合,因此速度越快

SELECT DISTINCT IF(from_users_id = $id, to_users_id, from_users_id) as user_id
FROM messages
WHERE from_users_id = $id OR to_users_id = $id;

thx代表您的回复相对性pNewbie,但a.user_id代表什么。(我得到一个空查询)
a.
是子查询的别名,由
定义为a
,在结束括号后,
user\u id
是分配给我们在子查询中选择的列的别名。Kirill Stadler的答案也应该适用。如果列名正确,那么在表定义中,您声明的
来自用户id
在代码中,您引用的
来自用户id
没有UNION不一定更快;或条件往往会导致忽略索引。
SELECT DISTINCT IF(from_users_id = $id, to_users_id, from_users_id) as user_id
FROM messages
WHERE from_users_id = $id OR to_users_id = $id;