Say I have a table of entries and a 2nd table of related entries:
Table 1:
id | data |
---|---|
1 | foo |
2 | bar |
Say I have a table of entries and a 2nd table of related entries:
Table 1:
id | data |
---|---|
1 | foo |
2 | bar |
Table 2:
id | related_to | data |
---|---|---|
1 | 1 | ding |
2 | 1 | dong |
Is there a way to write a query that returns data like this:
[
{
id: 1,
data: foo,
related_stuff: [
{
id: 1,
data: ding
},
{
id: 2,
data: dong
}
]
},
{
id: 2,
data: bar,
related_stuff: []
}
]
There are aggregate functions that combine single entries together to one aggregated list, mostly returned as strings, but I just want the entire dataset as an object (I work with JS mostly but the kind of language the database is bound to should be irrelevant here).
Example:
SELECT t1.id as id, t1.data as data, COUNT(t2.id) as amount
FROM t1
LEFT JOIN t2 ON t1.id = t2.related_to
GROUP BY t1.id
I would think something akin to this:
SELECT t1.id as id,
t1.data as data,
SELECT * FROM t2
WHERE t2.related_to = t1.id
as related_stuff
FROM t1
But I get an error that entries from the subquery must have at most 1 column.
Right now our code simply queries the entries of Table 1 and then does a query to Table 2 for each entry returned by Table 1 but I feel like there should be a way to write a single SQL query that returns the entirety in one query.
Share Improve this question edited Feb 10 at 12:50 Lelio Faieta 6,6849 gold badges47 silver badges84 bronze badges asked Feb 10 at 12:25 salbeirasalbeira 2,6115 gold badges28 silver badges44 bronze badges 7 | Show 2 more comments1 Answer
Reset to default 1Actually, it would vary based on the dbms.
For postgres
you can try using json_agg
in this way.
SELECT
t1.id,
t1.data,
COALESCE(json_agg(
json_build_object('id', t2.id, 'data', t2.data)
) FILTER (WHERE t2.id IS NOT NULL), '[]') AS related_stuff
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.related_to
GROUP BY t1.id, t1.data;
But, this wouldn't work with sqlite
, that has something called json_group_array
.
WHERE
). In both cases, use a hashmap/dictionary to putrelated_stuff
columns into a nested child list. SQL just doesn't work the way you are thinking, that's more like an object database such as MongoDB. – Charlieface Commented Feb 10 at 13:04