I have three tables
Owner
-----------------------
id | long
name | string
Animal
-----------------------
id | long
status | string
external_d | string
region | long (fk to region table)
owner_id | long (fk to owner table)
Region
-----------------------
id | long
name | string
I want to get multiple rows from the Animal table. Each record should contain the id, status, externalId and region.
Each row should be a JSON object and all the results should be in an array. e.g
[
{id: 3, status: 'alive', externalId: 'abc90', regionId: 2},
{id: 9, status: 'dead', externalId: 'xuy12', regionId: 2},
{id: 13, status: 'alive', externalId: 'ter34', regionId: 2}
]
I have tried to make the query as follows.
SELECT JSON_ARRAY(
JSON_OBJECT(
'id', id,
'externalId', externalId,
'status', status,
'regionId', regionId
)
) as final_data
FROM
(SELECT
a.id as id,
a.external_id as externalId,
a.status as status,
a.region_id as regionId
FROM
myDB.animal a
WHERE a.owner_id=12) as data;
running the above query gives me all the required columns in JSON format but each row is an array instead of all JSON objects in a single array.
Can someone help me solve this.
>Solution :
You can use json_arrayagg() to return all JSON objects in a single array :
SELECT JSON_ARRAYAGG(
JSON_OBJECT(
'id', id,
'externalId', external_id,
'status', status,
'regionId', region_id
)
) as final_data
FROM animal
WHERE owner_id=12;