Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add condition to mysql json_arrayagg function

Tags:

mysql

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?

like image 903
jack miao Avatar asked Dec 28 '18 00:12

jack miao


People also ask

What is JSON_ARRAYAGG in MySQL?

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.

What is Json_unquote in MySQL?

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.

Which of the following functions create JSON values?

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”.


1 Answers

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;
like image 150
Barmar Avatar answered Oct 05 '22 03:10

Barmar