简体   繁体   中英

MySQL distinct select on multiple columns grouped by latest entry

在此处输入图片说明

For the inbox of my users I would like to obtain the subject of only the last message in a conversation.

As you can see the user with id 1 has 2 conversations going. One with the QA and one with the Admin. So I would like to obtain the subject of message id:4 and id:6.

I have tried to do this in a single query with DISTINCT and GROUP BY created_at without success. Both id and created_at can be used to obtain the last message in a conversation but I prefer to use created_at.

select 
  *,
  least   (from_user_id, to_user_id) as min_uid,
  greatest(from_user_id, to_user_id) as max_uid
from
  (select * from message order by id desc) as message_reversed
group by
  min_uid,
  max_uid
SELECT id
     , created_at
     , from_user_id
     , to_user_id
     , subject
     , text 
  FROM message m
  JOIN 
     ( SELECT MAX(id) max_id
         FROM message
        GROUP
           BY LEAST(from_user_id,to_user_id)
            , GREATEST(from_user_id,to_user_id)
     ) x
    ON x.max_id = m.id;

Given that the "id" is an auto-incrementing primary key and you know the id of the user you are working with, why don't you query like this?

SELECT `text` as `lastMessage` 
FROM `yourTable` 
WHERE `from_user_id` = 1 
ORDER BY `id` DESC 
LIMIT 0,1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM