简体   繁体   English

MySQL根据最新条目对多个列进行不同选择

[英]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. 如您所见,ID为1的用户进行了2次对话。 One with the QA and one with the Admin. 一个是质量检查人员,另一个是管理员。 So I would like to obtain the subject of message id:4 and id:6. 所以我想获得消息ID:4和ID:6的主题。

I have tried to do this in a single query with DISTINCT and GROUP BY created_at without success. 我尝试使用DISTINCT和GROUP BY created_at在单个查询中执行此操作,但未成功。 Both id and created_at can be used to obtain the last message in a conversation but I prefer to use created_at. 这两个ID和created_at可以用来获得在谈话的最后消息,但我更喜欢使用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? 鉴于“ id”是一个自动递增的主键,并且您知道所使用的用户的id,为什么不这样查询?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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