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

时间:2020-02-26 09:04:31

标签: php mysql sql wordpress-rest-api

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

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

我要打印包含该格式的JSON

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

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

SELECT * FROM database ORDER BY city COLLATE utf8_polish_ci

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

使用

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": "comp@example.com ", "company": "company one  ", "website": "comp1.com"}]
}, 
{
"city": "city_2", "companies": [{"id": 12, "email": "comp2@example.com", "company": "company two  ", "website": "comp2.com"}, 
{"id": 31, "email": "comp3@example.com", "company": "company three", "website": "comp3.com"}]
}
]