mysql - SQL 在 2 列中选择不同的值,无论其顺序如何?

标签 mysql

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

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

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

SELECT DISTINCT senderID, recipientID FROM messages

它当然将消息 5、6 和 7 视为不同的消息。我怎样才能让它认识到,如果发件人和收件人是同一个人,无论订单如何,都只算一个?

**** 更新 ****

我没有意识到这会成为一个问题...假设在上表中,我还有一个名为“注释”的列,但我不希望对其进行“独特性”分析。我只是希望它包含在最终的查询结果中。如何包含注释列(或任何其他列),同时只要求 senderID 和recipientID 不同?

最佳答案

您可以选择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
                 );

关于mysql - SQL 在 2 列中选择不同的值,无论其顺序如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43706458/

相关文章:

php - 如何从 MySQL 表中获取嵌套结果并链接到另一个表?

php - Current_timestamp -> PHP 日期()

php - 我应该如何在多个链接上存储唯一的统计信息?

php - php mySQL 无序列表(流程图)

php - 如果其中只有一个记录与另一个字段的给定 id 匹配,则返回非给定 id 的所有记录

mysql - rails : Find all records matching condition for any of the associated objects

php - 使用 WHERE 子句中的数组中的值多次运行 mysql 查询

mysql - 简单的MySQL连接问题

mysql - VB.Net 每日时间记录 MySQL

Mysql 行总和作为行值