简体   繁体   English

MySQL按concat值分组,并在每个组中获取第一个ID(UUID)

[英]MySQL group by concat value and get first id (UUID) within each group

I am struggling with this for several hours already. 我已经为此奋斗了几个小时。 I am coding a messaging system and my table has the following columns: 我正在编写消息传递系统,并且我的表包含以下列:

ID(UUID) | ID(UUID)| from_user_id(uuid) | from_user_id(uuid)| to_user_id(uuid) | to_user_id(uuid)| subject | 主题| body | 身体| created_at created_at

In inbox page I need to get the results grouped by subject+from_user_id. 在收件箱页面中,我需要将结果按subject + from_user_id分组。 That is required because if the subject is the same then it is a separate dialogue and from_user_id should be concatenated with subject to make sure that if the other user will send a message with the same subject it will not be merged with other dialogue. 这是必需的,因为如果主题相同,那么它将是一个单独的对话,并且from_user_id应该与主题串联在一起,以确保如果其他用户将发送具有相同主题的消息,则不会与其他对话合并。

Second thing is that for each group I need to get the first message to show as dialogue cover message. 第二件事是,对于每个小组,我需要获取第一条消息以显示为对话封面消息。 It would be pretty easy to solve problem if I has normal ID's used but instead I am using UUID,s so I cannot use min or max for them. 如果我使用普通ID,但使用UUID,则很容易解决问题,因此我不能为它们使用min或max。 So I need to use created_at field to determine which row is the last. 因此,我需要使用created_at字段来确定哪一行是最后一行。

I have tried many different approaches but I cannot get the result I need. 我尝试了许多不同的方法,但无法获得所需的结果。 Maybe anybody had similar problem before and has a solution? 也许有人以前有过类似的问题并且有解决方案?

select msg.id, msg.body, msg.created_at, concat(msg.from_user_id, msg.subject) as concat

from messages as msg 

where msg.to_user_id = '8d99eb39-24f8-4dd6-b984-9505cd3eb6b6' 


order by msg.created_at desc limit 10 offset 0

Basically you need the subquery to identify the last message in each thread, and then select against that subquery to get the details from each of those last messsages 基本上,您需要子查询来标识每个线程中的最后一条消息,然后针对该子查询进行选择以从每个最后一个消息中获取详细信息

select * from messages 
 where to_user_id = 'jim'
   and concat(from_user_id, subject, created_at)  in (

    select max(concat(from_user_id, subject, created_at)) 
    from messages
    where to_user_id = 'jim' 
    group by concat(from_user_id, subject))

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

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