Skip to content
Advertisement

SQL get most recent joined record

I’ve the following tables:

chat: chatId, jobId

chat_message: userId, chatId, message, created_at

chat_user: chatId, userId

Am trying to get the last message sent by a specific user for all chats he’s a part of. This is what I have so far (left join for debugging on null):

The problem with this query is that the LIMIT 1 makes chat_message results null beyond the first row of results.

Removing the limit returns the data but am getting all the messages vs just the latest one.

What am I missing here? I feel like the LIMIT might be in the wrong place. I also tried the following alternative with no success:

Expected:

Actual:

Advertisement

Answer

Am trying to get the last message sent by a specific user for all chats he’s a part of.

To optimize performance, I would recommend indexes on:

  • chat_message(chatid, created_at)
  • chat(userid, chatid)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement