i have table conversation
conversation_id | name | is_group |
---|---|---|
1 | Global chat | 1 |
2 | private chat | 0 |
and i have table messages
message_id | conversation_id | sender_id | text | created_at |
---|---|---|---|---|
1 | 1 | 1 | hello | 06-04-2023 14:00:00 |
2 | 1 | 1 | whatsup | 06-04-2023 14:01:00 |
3 | 2 | 1 | hello | 06-04-2023 14:50:00 |
4 | 2 | 1 | how are you? | 06-04-2023 14:51:00 |
i need to get with one query conversation list with last message, something like this:
conversation_id | name | is_group | sender_id | last_message_text | created_at |
---|---|---|---|---|---|
1 | Global chat | 1 | 1 | whatsup | 06-04-2023 14:01:00 |
2 | private chat | 0 | 1 | how are you? | 06-04-2023 14:51:00 |
i tried with two query
- to get all chat list
- to get last message of chat throught loop
2
Answers
You can use the
row_number
window function to assign a running number for messages per conversation, and then join on the last one:You can do it using
inner join
to join with a set of max created_at per conversation as follows :Demo here