mysql - 将 json Array 转换为 Json 对象并在 MySQL 上向其添加更多项目
问题描述
在 MySQL 表中,如何使用先前的值将当前保存 JSON 数组值的列的值转换为 JSON 对象数组?
当前列(仅包含 ID):
items
-------
[1,2,3]
[2,3]
...
所需格式:
items
-------
[ { id:1, lastUpdatedBy:"", timeStamp:"--" },{ id:2, lastUpdatedBy:"", timeStamp:"--" },{ id:3, lastUpdatedBy:"", timeStamp:"--" }]
[ { id:2, lastUpdatedBy:"", timeStamp:"--" },{ id:3, lastUpdatedBy:"", timeStamp:"--" }]
...
解决方案
如果您运行的是 MySQL 8.0,您可以使用 取消嵌套数组json_table()
,然后构建 json 对象并使用 聚合json_arrayagg()
。
为此,您需要一个主键 - 我假设pk
:
select json_arrayagg(json_object(
'id', i.id,
'lastUpdatedBy', 12,
'timestamp', '--'
)) items
from mytable t
cross join json_table(t.items, '$[*]' columns (id int path '$')) i
group by t.pk
如果你想update
查询:
update mytable t
inner join (
select json_arrayagg(json_object(
'id', i.id,
'lastUpdatedBy', 12,
'timestamp', '--'
)) items
from mytable t
cross join json_table(t.items, '$[*]' columns (id int path '$')) i
group by t.pk
) x on x.pk = t.pk
set x.items = t.items
推荐阅读
- vb.net - 在 vb.net 中创建一个连续的字母数字字符串
- reactjs - POST FETCH 在 SubmitSignIn 404 错误
- powershell - VSCode Powershell 终端 - 截断行
- r - 用 R 中的组中的非 NA 字符替换一组值的 NA
- c# - 标签未出现在 xamarin 应用 android 设备上
- javascript - 在axios中使用get请求下载文件
- c++ - 获取 std::array 的大小作为 r 值
- svg - 使用带有 SVG 的框架无法使其增长
- python - 是否可以实现一个上下文管理器来处理向 cuda 的张量传输
- node.js - 为什么我的 getServerSideProps 在 Vercel 上返回 404,但在 localhost 上却没有