1

我有以下查询:

"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”。

4

1 回答 1

2

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

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

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

于 2012-08-21T21:59:21.453 回答