说我有一个JSON列foo
,其中每个值都是对象数组,即:
[{"date": somedate, "value": somevalue, "othervaluesidontneed":...},
{"date": somedate, "value": somevalue, "othervaluesidontneed":...},
{"date": somedate, "value": somevalue, "othervaluesidontneed":...},...]
我想选择此列,但对于每一行,只包含键date
和value
,因此返回值是:
[{"date": somedate, "value": somevalue},
{"date": somedate, "value": somevalue},
{"date": somedate, "value": somevalue},...]
这可能吗?
答案 0 :(得分:2)
一种解决方案是使用json_table()
(仅在MySQ 8.0中可用)将数组扩展为一组行,然后生成一个新的对象数组,该对象数组仅包含带有{{1}的请求键}:
json_arrayagg()
这要求可以使用某些列来唯一标识初始表中的行:我称该列select
json_arrayagg(json_object( 'date', tt.date, 'value', tt.value)) new_js
from
mytable t,
json_table(
js,
"$[*]"
columns(
date datetime path "$.date",
value int path "$.value"
)
) as tt
group by t.id
。
id
| new_js | | :----------------------------------------------------------------------------------------------------------------------------------------------------------- | | [{"date": "2019-01-01 00:00:00.000000", "value": 1}, {"date": "2019-01-02 00:00:00.000000", "value": 2}, {"date": "2019-01-03 00:00:00.000000", "value": 3}] |