结合mySQL查询中的常用值

时间:2012-08-21 21:55:43

标签: 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"

得到以下结果:

to    fromEmail
887   1923
1923  887
1637  887
370   887

问题:我怎样才能避免前两个意义上的重复值,即使它们是相反的,它们仍然被认为是重复的“887 1923”和“1923 887”。

1 个答案:

答案 0 :(得分: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,那么逻辑会有点复杂,但它仍然是相同的想法:在执行不同之前按特定顺序排序值。