Sql SELECT DISTINCT - How can I select distinct couple without considering columns' order?

烂漫一生 提交于 2019-12-12 01:27:52

问题


I have a table like this

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

and I want to select only the couples in which A is. I mean, I want the rows:

 0 | EmailA | EmailB
 1 | EmailA | EmailC 

I don't care if I'll get

 0 | EmailA | EmailB 

or

 1 | EmailB | EmailA

because in my case A,B is the same as B,A but I need it only once.

I saw many answers to questions like this but I can't solve my problem. Thank you very much.


回答1:


Please, check if this query solves the problem (just change TMP_STACK with your table name):

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



回答2:


I solved using this query:

$sql="SELECT Sender, Receiver FROM Messages WHERE Sender <= Receiver UNION SELECT Receiver, Sender FROM Messages WHERE Receiver < Sender";




回答3:


select * from inbox where (sender = 'myself' and receiver='target') or (sender = 'target' and receiver='myself') order by since



来源:https://stackoverflow.com/questions/39276975/sql-select-distinct-how-can-i-select-distinct-couple-without-considering-colum

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!