I am struggling with this for several hours already. I am coding a messaging system and my table has the following columns:
ID(UUID) | from_user_id(uuid) | to_user_id(uuid) | subject | body | created_at
In inbox page I need to get the results grouped by 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.
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. So I need to use created_at field to determine which row is the last.
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))
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.