Say I have a table of people:
+----+------+
| id | name |
+----+------+
| 1 | John |
| 2 | Mary |
| 3 | Jane |
+----+------+
And various tables for clothing of various types, e.g. a table of shoes
+----+----------+--------------------+---------+
| id | brand | name | type |
+----+----------+--------------------+---------+
| 1 | Converse | High tops | sneaker |
| 2 | Clarks | Tilden cap Oxfords | dress |
| 3 | Nike | Air Zoom | running |
+----+----------+--------------------+---------+
And then for each clothing type, I have a junction table recording what items of that type each person owns:
+--------+---------+
| person | shirt |
+--------+---------+
| 1 | 3 |
| 1 | 4 |
| 2 | 2 |
...
I need a query that compiles these tables into a return like so:
+----+------+--------------------+
| id | name | clothing items |
+----+------+--------------------+
| 1 | John | [JSON in a string] |
| 2 | Mary | [JSON in a string] |
| 3 | Jane | [JSON in a string] |
+----+------+--------------------+
Where the [JSON in a string]
for each row should look like this:
[
{"type":"shirt","id":3},
{"type":"shirt","id":4},
{"type":"pant","id":2},
{"type":"shoe","id":5}
]
How do I go about constructing this query in SQLITE? If needed, it’s easy for me to define my own custom aggregate function.
2
Answers
Figured it out:
See dbfiddle for demo
You can get you result by using this query. I t first json object then groups them into an array from each user id and name array: