Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.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
在mySQL查询中组合公共值_Mysql_Sql - Fatal编程技术网

在mySQL查询中组合公共值

在mySQL查询中组合公共值,mysql,sql,Mysql,Sql,我有以下疑问: "SELECT DISTINCT `emails`.`to`,`emails`.`from` as fromEmail FROM `emails` WHERE ((`emails`.`from` = '".$loggedMember->id."') OR (`emails`.`to` = '".$loggedMember->id."')) AND (`emails`.`to` != 0) ORDER BY `id` DESC LIMIT 4" 并得到如下结果:

我有以下疑问:

"SELECT DISTINCT `emails`.`to`,`emails`.`from` as fromEmail 
FROM `emails` WHERE ((`emails`.`from` = '".$loggedMember->id."') 
OR (`emails`.`to` = '".$loggedMember->id."')) 
AND (`emails`.`to` != 0) ORDER BY `id` DESC LIMIT 4"
并得到如下结果:

to    fromEmail
887   1923
1923  887
1637  887
370   887

问题:如何避免前两种意义上的重复值,即使它们是相反的,它们仍然被认为是重复的“887 1923”和“1923 887”。

要消除重复值,您需要将电子邮件按规范顺序排列:

SELECT DISTINCT
       (case when `emails`.`to` < `emails`.`from` then `emails`.`to`
             else `emails`.`from`
        end) as email1,
       (case when `emails`.`to` >= `emails`.`from` then `emails`.`to`
             else `emails`.`from`
        end) as email2
FROM `emails`
WHERE ((`emails`.`from` = '".$loggedMember->id."')  OR (`emails`.`to` = '".$loggedMember->id."')) AND (`emails`.`to` != 0)
ORDER BY `id` DESC LIMIT 4
选择DISTINCT
(当'emails`.`到`` emails`.`从`然后'emails`.`到`
其他“电子邮件”来自`
完)作为电子邮件1,
(当`emails`.`to`>=`emails`.`from`then`emails`.`to`时的大小写)`
其他“电子邮件”来自`
(完)电邮2
来自`电子邮件`
其中(`emails`.`from`='”$loggedMember->id.“')或(`emails`.`to`='”$loggedMember->id.“')和(`emails`.`to`!=0)
按'id'订购说明限制4

如果字段可以是空的,那么逻辑会稍微复杂一些,但仍然是相同的想法:在执行distinct之前按特定顺序对值排序。

@mellamokb。我非常尊重那些胡乱回答问题的人;)