Skip to content
Advertisement

Get room members, room’s owner and admin at the same time in one query with grouped by id (unique) on PostgreSQL 12

I want to get room’s member list, room’s owner member in case of he doesn’t exists in other table and admin member at the same time. Currently i fetch them individually.

What I want is:

  1. room_members list of ‘My Room’ (Which is only Mike at the moment)
  2. My Room’s owner in case of he didn’t add himself to room_members table. Because he is the owner of that room (Which is April)
  3. Plus, admin member (Which is Pratha)

And this should be unique. For example, if user add himself to room_members and also owner then it should fetch member one time only.

What I tried so far?

I couldn’t use group by here either. Also i don’t need the all fields. Just room_members table fields only.

See here: https://rextester.com/XWDS42043

Expected output for room_members:

  • Pratha: Because he is ADMIN
  • Mike: Because he is member of My Room. MEMBER
  • April: Because she created that room. OWNER

room_members can be many. I just added only Mike but it can have multiple members including admins and owners.

Advertisement

Answer

You can address this with UNION:

UNION eliminates duplicates accross queries, so if a user is both member and/or group admin and/or owner of the room, they will only appear once.

In your fiddle, this query returns:

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