samedi 3 décembre 2016

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) | 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



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2fWWUZC
via IFTTT

Aucun commentaire:

Enregistrer un commentaire