I have a json query that gives me json of a joined table of person and pets:
SELECT json_object(
'personId', p.id,
'pets', json_arrayagg(json_object(
'petId', pt.id,
'petName', pt.name
))
)
FROM person p LEFT JOIN pets pt
ON p.id = pt.person_id
GROUP BY p.id;
my issue is that person can have 0 or more pets, and when a person have 0 pets I get list with 1 empty pet, and what I would like to get in that case is empty list.
this is what I get:
{
"personId": 1,
"pets": [
{
"petId": null,
"petName": ""
}
]
}
and I need:
{
"personId": 1,
"pets": []
}
is that possible?
JSON_ARRAYAGG( col_or_expr ) Aggregates a result set as a single JSON array whose elements consist of the rows. The order of elements in this array is undefined. The function acts on a column or an expression that evaluates to a single value. Returns NULL if the result contains no rows, or in the event of an error.
JSON_UNQUOTE() – Remove Quotes from a JSON Document in MySQL In MySQL, the JSON_UNQUOTE() function “unquotes” a JSON document and returns the result as a utf8mb4 string. You provide the JSON document as an argument, and the function will do the rest.
Two aggregate functions generating JSON values are available. JSON_ARRAYAGG() returns a result set as a single JSON array, and JSON_OBJECTAGG() returns a result set as a single JSON object. For more information, see Section 12.20, “Aggregate Functions”.
The problem is that LEFT JOIN
still returns columns from the table you're joining with, it just sets their values to NULL
.
You can use IF
to test COUNT(pt.id)
, as this won't count null values.
SELECT json_object(
'personId', p.id,
'pets', IF(COUNT(pt.id) = 0, JSON_ARRAY(),
json_arrayagg(json_object(
'petId', pt.id,
'petName', pt.name
)
))
)
FROM person p LEFT JOIN pets pt
ON p.id = pt.person_id
GROUP BY p.id;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With