使用 MySQL 生成 JSON 输出

Generate JSON output with MySQL

我有 2 个表,其中:

Table 1: 姓名

| id | first_name | last_name |
|----|------------|-----------|
| 1  | John       | Doe       |
| 2  | Jane       | Doe       |

Table 2: phone

| rec | id |  type  |    number    |
|-----|----|--------|--------------|
| 1   | 1  | Home   | 123-123-1234 |
| 2   | 1  | Work   | 234-234-2345 |
| 3   | 1  | Mobile | 345-345-3456 |
| 4   | 2  | Mobile | 456-456-4567 |

如果我运行下面的查询:

SELECT name.*, phone.type, phone.number
FROM name, phone
WHERE name.id = phone.id

它将产生以下结果:

| id | first_name | last_name |  type  |    number    |
|----|------------|-----------|--------|--------------|
| 1  | John       | Doe       | Home   | 123-123-1234 |
| 1  | John       | Doe       | Work   | 234-234-2345 |
| 1  | John       | Doe       | Mobile | 345-345-3456 |
| 2  | Jane       | Doe       | Mobile | 456-456-4567 |

有没有办法将查询输出生成到 JSON 中,使其看起来像这样:

{
    "data": [{
        "id": 1,
        "first_name": "John",
        "last_name": "Doe",
        "phone": [{
                "type": "Home",
                "number": "123-123-1234"
            },
            {
                "type": "Work",
                "number": "234-234-2345"
            },
            {
                "type": "Mobile",
                "number": "345-345-3456"
            }
        ]
    }, {
        "id": 2,
        "first_name": "Jane",
        "last_name": "Doe",
        "phone": [{
            "type": "Mobile",
            "number": "456-456-4567"
        }]
    }]
}

您可以使用以下内容并查看下面的工作 fiddle:


SELECT JSON_OBJECT(
   "data",JSON_ARRAYAGG(results)
) as final_result
FROM (
    SELECT 
        JSON_OBJECT(
          "id",name.id,
          "first_name",name.first_name,
          "last_name",name.last_name,
          "phone",JSON_ARRAYAGG(
               JSON_OBJECT(
                  "type",phone.type,
                  "number",phone.number
               )
          )
        ) as results
    FROM name
    INNER JOIN phone ON phone.id = name.id
    GROUP BY name.id,first_name,last_name
 ) t




final_result
{"data": [{"id": 1, "phone": [{"type": "Home", "number": "123-123-1234"}, {"type": "Work", "number": "234-234-2345"}, {"type": "Mobile", "number": "345-345-3456"}], "last_name": "Doe", "first_name": "John"}, {"id": 2, "phone": [{"type": "Mobile", "number": "456-456-4567"}], "last_name": "Doe", "first_name": "Jane"}]}

View on DB Fiddle