0

I'm trying preparing an array of objects using MySQL

my query look like this

SELECT c.id AS classRoomId, 
JSON_ARRAYAGG(json_object("studentId", st.id, "studentName", st.name)) AS students
FROM branch b
LEFT JOIN classRoom c ON b.id = c.id
LEFT JOIN students st ON c.id = st.id
WHERE b.id = 2
GROUP BY c.id

the above query returns list students by classRoom in a particular branch/institute, for the above query im getting the result like this

classRoomId students
1 [{"studentId": 1, "studentName": "a"}, {"studentId": 2, "studentName": "b"}]
2 [{"studentId": 3, "studentName": "c"}, {"studentId": 4, "studentName": "d"}]
3 [{"studentId": null, "studentName": null}]

Here problem is, if there are no students in a class then it is retuning null values like ({"studentId": null, "studentName": null}). so is it possible to return an empty array ([]) if there are no students

3
  • You can use COALESCE(...your JSON expression..., CAST('[]' AS JSON)). Commented Oct 11, 2022 at 17:14
  • But I think you have other problems in your query. Is it really correct that branch.id = classRoom.id = students.id? Commented Oct 11, 2022 at 17:15
  • maybe - "IF(st.id is null,'([])', JSON_ARRAYAGG(json_object("studentId", st.id, "studentName", st.name)))" Commented Oct 11, 2022 at 17:18

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.