MySQL 将数据附加到 JSON 数组中的每个 JSON 对象

MySQL append data to each JSON Object within JSON Array

在此 table - mytable 我有一个 json 列 - col 及其内容
[{"id": 1, "data1": "abc", "data2": "xyz"}, {"id": 2, "data1": "def", "data2": "ghi"}]

还有一个 table - product

+----+---------+
| id | name    |
+----+---------+
|  1 | pro 1   |
+----+---------+
|  2 | pro 2   |
+----+---------+

有没有一种方法可以将名称附加到 JSON 数组中的每个 JSON 对象 例如- [{"id": 1,"name":"pro 1", "data1": "abc", "data2": "xyz"}, {"id": 2,"name":"pro 2", "data1": "def", "data2": "ghi"}]

在 MySQL 8.0 中,您可以为此使用 json_table()。这个想法是将 json 数组取消嵌套到行,加入 product table 然后重新聚合。

select json_arrayagg(
    json_object(
        'id',    x.id,
        'data1', x.data1,
        'data2', x.data2,
        'name',  p.name
    )
) as col
from mytable t
cross join json_table(
    t.col, 
    '$[*]' columns ('id' int, 'data1' varchar(50), 'data2' varchar(50))
) x
inner join product p on p.id = x.id
group by x.id