Skip to content

Instantly share code, notes, and snippets.

@geekuillaume
Created August 3, 2018 12:27
Show Gist options
  • Save geekuillaume/0ccaee3b392e3f7eff1b5d765f649d5b to your computer and use it in GitHub Desktop.
Save geekuillaume/0ccaee3b392e3f7eff1b5d765f649d5b to your computer and use it in GitHub Desktop.
Using jsonb_agg
SELECT todo_lists.id AS todo_list_id,
todo_lists.name,
todo_items.id AS todo_item_id,
todo_items.name
FROM todo_ LISTS
LEFT JOIN todo_items ON todo_items.todo_list_id = todo_lists.id;
+----------------+-------------------------+----------------+-----------------------------------------------+
| todo_list_id | name | todo_item_id | name |
|----------------+-------------------------+----------------+-----------------------------------------------|
| 0 | methodologies capacitor | 0 | maroon open-source |
| 0 | methodologies capacitor | 1 | matrix Suriname |
| 0 | methodologies capacitor | 2 | e-tailers Kyat |
| 1 | Music workforce | 3 | violet SSL |
| 1 | Music workforce | 4 | Beauty European Unit of Account 17(E.U.A.-17) |
| 1 | Music workforce | 5 | vortals Michigan |
| 2 | Concrete Fantastic | 6 | Frozen indigo |
| 2 | Concrete Fantastic | 7 | wireless Assistant |
| 2 | Concrete Fantastic | 8 | archive Denar |
+----------------+-------------------------+----------------+-----------------------------------------------+
SELECT todo_lists.id AS todo_list_id,
todo_lists.name,
jsonb_agg(to_jsonb(todo_items) - 'todo_list_id') AS items
FROM todo_lists
LEFT JOIN todo_items ON todo_items.todo_list_id = todo_lists.id
GROUP BY todo_lists.id;
+----------------+-------------------------+----------------------------------------------------------------------------------------------------------------------------------------------+
| todo_list_id | name | items |
|----------------+-------------------------+----------------------------------------------------------------------------------------------------------------------------------------------|
| 0 | methodologies capacitor | [{"id": 0, "name": "maroon open-source"}, {"id": 1, "name": "matrix Suriname"}, {"id": 2, "name": "e-tailers Kyat"}] |
| 1 | Music workforce | [{"id": 3, "name": "violet SSL"}, {"id": 4, "name": "Beauty European Unit of Account 17(E.U.A.-17)"}, {"id": 5, "name": "vortals Michigan"}] |
| 2 | Concrete Fantastic | [{"id": 6, "name": "Frozen indigo"}, {"id": 7, "name": "wireless Assistant"}, {"id": 8, "name": "archive Denar"}] |
+----------------+-------------------------+----------------------------------------------------------------------------------------------------------------------------------------------+
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment