I have two tables, ChatRoom and ChatRoomMap, I want to get a list of chatrooms a user belongs to, along with all the other users in each chatroom.
// this contains a map of user to chatroom, listing which user is in what room
CREATE TABLE ChatRoomMap
(
  user_id bigint NOT NULL,
  chatroom_id text NOT NULL,
  CONSTRAINT uniq UNIQUE (userid, roomid)
)
// sample values
==========================
| user_id  | chatroom_id | 
|    1     |      7      |
|    1     |     blue    |
|    7     |     red     |
==========================
And
CREATE TABLE ChatRoom 
(
  id text NOT NULL,
  admin bigint,
  name text,
  created timestamp without time zone NOT NULL DEFAULT now(),
  CONSTRAINT uniqid UNIQUE (id)
)
// sample values
======================================================
|    id    |    admin    |    name      |  timestamp |
|   blue   |      7      |   blue room  |    now()   |
|   red    |      2      |    red       |    now()   |
|    7     |     11      |   mine       |    now()   |
======================================================
To get a list of rooms a user is in, I can do:
SELECT DISTINCT ON (id) id, userid, name, admin 
FROM ChatRoomMap, ChatRoom WHERE ChatRoomMap.user_id = $1 AND ChatRoomMap.chatroom_id = ChatRoom.id
This will get me a distinct list of chat rooms a user is in.
I would like to get the distinct list of rooms along with all the users in each room (concatenation of all as a separate column), how can this be done?
Example result:
=======================================================
| user_id  | chatroom_id | name | admin | other_users |
|    10    |     7       | One  |   1   | 1, 2, 3, 8  |
|    10    |     4       | AAA  |   10  | 7, 11, 15   |
=======================================================
 
    