How to group multiple values into one based on specific column value?

MMPL1 :

I'm working on my project and I need some help. I'm making my custom endpoint in wordpress. Everything works fine except one thing. I have database

| id |  city  | company       | email             | website
--------------------------------------------------------------
| 22 | city_1 | company one   | [email protected]  | comp1.com
--------------------------------------------------------------
| 12 | city_2 | company two   | [email protected] | comp2.com
--------------------------------------------------------------
| 31 | city_2 | company three | [email protected] | comp3.com
--------------------------------------------------------------
| 72 | city_3 | company four  | [email protected] | comp4.com

I want to print JSON which contains that format

   {
      "city":"city_1",
      "companies": [
        {
         "id":"22",
         "email":"[email protected]",
         "website":"comp1.com"
        }
      ],
   },
   {
      "city":"city_2",
      "companies": [
        {
         "id":"12",
         "email":"[email protected]",
         "website":"comp2.com"
        },
        {
         "id":"31",
         "email":"[email protected]",
         "website":"comp3.com"
        }
      ],
   },
   {
      "city":"city_4",
      "companies": [
        {
         "id":"72",
         "email":"[email protected]",
         "website":"comp4.com"
        }
      ],
   },

So, I want to group multiple values into one based on city value. How Can I do it? I tried with GROUP BY statement but it gives me one row. My current SQL query

SELECT * FROM database ORDER BY city COLLATE utf8_polish_ci

Thanks for any help!

Naveen Arora :

Use

JSON_ARRAYAGG

select JSON_ARRAYAGG(JSON_OBJECT('city',city,'companies',companies)) from (
select city,JSON_ARRAYAGG(JSON_OBJECT('id',id,'company', 
company,'email',email,'website',website)) as companies from test group by city
)t;

This will print the expected output in JSON format.

Output:

[
{
"city": "city_1", "companies": [{"id": 22, "email": "[email protected] ", "company": "company one  ", "website": "comp1.com"}]
}, 
{
"city": "city_2", "companies": [{"id": 12, "email": "[email protected]", "company": "company two  ", "website": "comp2.com"}, 
{"id": 31, "email": "[email protected]", "company": "company three", "website": "comp3.com"}]
}
]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=13887&siteId=1