Sql SELECT DISTINCT - 如何在不考虑列的顺序的情况下选择不同的一对?

时间:2016-09-01 16:52:25

标签: select distinct

我有一张这样的表

ID | Sender | Receiver
 0 | EmailA | EmailB
 1 | EmailB | EmailA
 2 | EmailA | EmailB
 3 | EmailA | EmailC
 4 | EmailC | EmailA 
...

我想只选择A所在的夫妻。我的意思是,我想要行:

 0 | EmailA | EmailB
 1 | EmailA | EmailC 

我不在乎我是否会

 0 | EmailA | EmailB 

 1 | EmailB | EmailA

因为在我的情况下A,B与B,A相同,但我只需要它一次。

我看到很多这样的问题的答案,但我无法解决我的问题。非常感谢你。

3 个答案:

答案 0 :(得分:0)

请检查此查询是否解决了问题(只需使用您的表名更改TMP_STACK):

WITH 
q AS  (
       SELECT DISTINCT a.sender,
                       a.receiver,
                       a.sender || a.receiver AS concat
       FROM TMP_STACK a
       WHERE a.sender LIKE '%A'
      ),
qq AS (
       SELECT MAX(id) as id,
              a.sender || a.receiver AS concat
       FROM TMP_STACK a
       WHERE a.sender LIKE '%A'
       GROUP BY a.sender || a.receiver
      )
SELECT qq.id,
        q.sender,
        q.receiver
FROM q
LEFT JOIN qq ON q.concat = qq.concat

答案 1 :(得分:0)

我使用此查询解决了:

$ sql =" SELECT Sender,Receiver FROM Messages WHERE Sender< = Receiver UNION SELECT Receiver,Sender FROM Messages WHERE Receiver<发件人&#34 ;;

答案 2 :(得分:0)

从收件箱中选择*,其中(sender ='我'和收件人='目标')或(发件人='目标'和收件人='我自己')从此开始