Skip to content
Advertisement

How to construct SQL query to select chat participants

I have 3 tables. Users(id, fullname), Chats(id, name) and Chats_Participants(chatId, userId). I need to select all the chats in which user with specified id consists. For example:

Chats:
1. 1, ‘Test’

Users:
1. 1, ‘Test user’
2. 2, ‘Test user2’

Chat_Participants:
1. 1(chatId), 1(userId)
2. 1(chatId), 2(userId)

As a result, I need something like this:
1(chatId) ‘Test'(chatName) participants(array of users in chat)

First I’ve wrote this:

but this query selects only one participant

Advertisement

Answer

You can try with array_agg in postgresql. Demo here. Users table is not linked here, printing user id from chat_participants table instead.

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