Skip to content
Advertisement

Fetch multi-participant conversations with last message for each

I am trying to create a simple chat application database schema, and query the conversations. My current table setup is the following:

So basically each conversation has its own title, and multiple participants. What I would like to fetch my conversations sorted by the date of the latest message in the conversation (so the conversations with the newest messages are shown first). The result set should contain the id, title of the conversation and list of participants + the id, sender_id and body of the latest message.

It would also be required to fetch the conversations paginated based on the creation date of the conversation (20 per page)

Is my table setup efficient enough to satisfy the above constraint? Seems to me that this could result in a rather large query with multiple subqueries?.

Advertisement

Answer

To get latest message for your conversations there are ways to achieve it like self joins or window functions (row_number(), rank() etc). Using window function you can write your query as

DEMO

In above query I have used left joins to include conversions with no messages, If you need only conversations which has messages then use inner joins. If you need more than 1 latest messages for each conversation change cm.r <= @no

To get participants list for each conversation you can add new CTE like

DEMO

Improvements

  • Add user_id in conversation table to identify who has created this conversation.

  • Table conversation_participant is redundant while you can extract list of participants from conversation_message

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement