SQL在两列中选择DISTINCT值而不管它们的顺序如何?

时间:2017-04-30 12:38:44

标签: mysql

这看起来应该是如此简单,但对于我的生活,我无法在任何地方找到答案。假设我有以下数据:

public class Hashing {
    public static void main(String[] args) {
        // String s1=new String("a");
        // String s2=new String("b");
        Hashing s1=new Hashing();
        Hashing s2=new Hashing();
        System.out.println(s1.equals(s2));
        // output -> true
    }
    @Override
    public int hashCode() {
        return 1;
    }
    @Override
    public boolean equals(Object arg0) {
        return true;
    }
}

我只想选择唯一的对话。所以对我来说,消息5(15,999),6(999,15)和7(15,999)来自同一个对话,需要只显示一次而不是3次。如果我使用SQL语句:

messageID  senderID recipientID 
        2       999           6
        4        23         999
        5        15         999 
        6       999          15
        7        15         999 

当然,它将消息5,6和7视为不同的消息。我怎样才能让它认识到,如果发件人和收件人是相同的,不管订单是什么,它只被算作一个?

****更新****

我没有意识到的事情会是一个问题...让我们在上面的表格中说,我也有一个名为“笔记”的栏目,但我不希望它被分析为“清晰度”。我只想将它包含在最终的查询结果中。我怎样才能包含notes列(或任何其他列),同时只要求senderID和recipientID是不同的?

2 个答案:

答案 0 :(得分:1)

您可以查看least()greatest()

select distinct least(senderID, recipientID) as id1, greatest(senderID, recipientID) as id2
from messages m;

如果要确保结果行实际位于原始表中:

select distinct senderId, recipientId 
from messages m
where senderId <= recipientId
union all
select distinct senderId, recipientId  
from messages m
where senderId > recipientId and
      not exists (select 1 from messages m2
                  where m2.senderId = m.recipientId and
                        m2.recipientId = m.senderId
                 );

答案 1 :(得分:0)

尝试:

SELECT DISTINCT 
    case when senderID > recipientID then recipientID else senderID end lowerID,
    case when senderID < recipientID then recipientID else senderID end higherID
FROM messages
相关问题