I have two tables A and B.
A (id int PRIMARY_KEY, json_field JSON)
B (a_id FOREIGN_KEY, value int)
The relationship is One To Many. So A.id might occur several times in B.a_id. So the tables could look something like this:
A:
id ___ json_field
1 null
2 null
B:
a_id ___ value
1 100
1 101
2 200
2 201
Now I need a query that puts the ID-matching values into the json_field as an array.
So the result should look something like:
A:
id ___ json_field
1 [100, 101]
2 [200, 201]
We can assume that the json_fields are initially empty.
I guess this could be done with a subquery, but I can’t quite figure out how.
Update A
Set json_field = CREATE JSON FROM RESULTSET (
SELECT value
FROM A, B
WHERE A.id = B.a_id)
2
Answers
The simplest way will be to use String Functions
but usually you don’t want to store data twice in a database, you can as you see below always create the output wanted add every time
Also you should read the thread about storing delimited data
if the values must be in a fixed order your B table needs a sorting column so that GROUP_CONCAT can sort them in the wanted order
100,
101
]
200,
201
]
fiddle
Try using json_arrayagg:
Output:
To update the A table we could use an update with join or with a correlated sub-query as the following:
demo