mysql 2列值的唯一组合按另一列排序

时间:2017-08-18 15:08:43

标签: mysql

我有这样的样本数据

------------------------------------------
message_id | sender_id | receiver_id | message
------------------------------------------

1 | 101 | 102 | hello
2 | 102 | 101 | i am fine
3 | 103 | 101 | where are you?
4 | 101 | 103 | i am at my home
5 | 103 | 101 | ok
6 | 101 | 102 | so whats up?
7 | 102 | 104 | i am so busy
8 | 105 | 101 | hey

我想要用户101是参与者的每个对话的最新消息

期待输出

8 | 105 | 101 | hey
6 | 101 | 102 | so whats up?
5 | 101 | 103 | i am at my home

我需要mysql查询。

提前感谢。

3 个答案:

答案 0 :(得分:1)

E.g:

SELECT a.* 
  FROM my_table a 
  JOIN 
     ( SELECT LEAST(sender_id,receiver_id) user1
            , GREATEST(sender_id,receiver_id) user2
            , MAX(message_id) message_id 
         FROM my_table 
        WHERE 101 IN (sender_id,receiver_id)
        GROUP 
           BY user1
            , user2
     ) b 
    ON b.message_id = a.message_id;

或只是

SELECT a.* 
  FROM my_table a 
  JOIN 
     ( SELECT MAX(message_id) message_id 
         FROM my_table 
        WHERE 101 IN (sender_id,receiver_id)
        GROUP 
           BY LEAST(sender_id,receiver_id) 
            , GREATEST(sender_id,receiver_id) 
     ) b 
    ON b.message_id = a.message_id;

这也可以写成如下。我怀疑它对性能有多大影响......

SELECT a.* 
  FROM my_table a 
  JOIN 
     ( SELECT MAX(message_id) message_id
         FROM 
            ( SELECT message_id
                   , receiver_id user2 
                FROM my_table 
               WHERE sender_id = 101
               UNION
              SELECT message_id
                   , sender_id 
                FROM my_table 
               WHERE receiver_id = 101
            ) x
        GROUP
           BY user2
     ) b 
    ON b.message_id = a.message_id;

实际上,在我自己的有限测试中,第一个查询的完成时间是最后一个查询的一半。

答案 1 :(得分:-1)

如果您提供位代码或您的文件sql将很好地回答您的问题。 试试这个:

$query = mysqli_query($connection," SELECT * FROM your table WHERE sender_id = '101' OR receive_id = '101' GROUP BY message_id ");
return $query;

答案 2 :(得分:-2)

您可以使用此命令

SELECT * FROM table_name WHERE sender_id=101 OR receiver_id =101

这将对数据进行排序并为您提供所需的结果