Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return column of joined rows as array instead of object

I’m having a problem which is a little difficult for me to explain.

I have two database tables:

| ID | FRUIT |
| 1  | Apple |
| 2  | Orange|
| FRUIT_ID | COLOR |
| 1       | Red   |
| 1       | Green |
| 2       | Orange|

The idea behind this: A Fruit can have multiple colors.
To get all the colors from all the fruits I have to join them:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT a.*, b.color FROM Fruit a, FruitColor b WHERE a.id = b.fruit_id

| ID | FRUIT | COLOR |
| 1  | Apple | Red   |
| 1  | Apple | Green |
| 2  | Orange| Orange|

The Json would look like this:

[{
    ID: "1",
    FRUIT: "Apple",
    COLOR: "Red"
},
{
    ID: "1",
    FRUIT: "Apple",
    COLOR: "GREEN"
},
{
    ID: "2",
    FRUIT: "Orange",
    COLOR: "Orange"
}]

And here comes the problem
I actually don’t want to return an object for every extra color, I need them in an array like this:

[{
    ID: "1",
    FRUIT: "Apple",
    COLOR: ["Red", "Green"]
},
{
    ID: "2",
    FRUIT: "Orange",
    COLOR: "Orange"
}]

How can I achieve this?
It doesn’t matter if I have to change the DB structure or the query, any solution to this would help.

>Solution :

You can use JSON_ARRAYAGG function twice in order to encapsulate the colors firstly, and objects with the second apply such as

SELECT JSON_ARRAYAGG(js) AS Result
  FROM (SELECT JSON_OBJECT('id',
                           f.id,
                           'fruit',
                           f.fruit,
                           'state',
                           JSON_ARRAYAGG(fc.color)) AS js
          FROM Fruit AS f
          JOIN FruitColor AS fc
            ON f.id = fc.fruit_id
         GROUP BY f.id, f.fruit) j

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading