如何根据特定的列值将多个值分组为一个?

问题描述 投票:0回答:1

我正在做我的项目,我需要一些帮助。我在wordpress中创建自定义端点。除了一件事,一切都正常。我有数据库

| 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

我想打印包含该格式的JSON

   {
      "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"
        }
      ],
   },

因此,我想根据城市价值将多个值分组为一个。我该怎么做?我尝试使用GROUP BY语句,但是它给了我一行。我当前的SQL查询

SELECT * FROM database ORDER BY city COLLATE utf8_polish_ci

感谢您的帮助!

php mysql sql wordpress-rest-api
1个回答
2
投票

使用

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;

这将以JSON格式打印预期的输出。

输出:

[
{
"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"}]
}
]
© www.soinside.com 2019 - 2024. All rights reserved.