我有一个表,其中有一列是 TEXT 列,但我们在那里存储 json 数据。 json 数据如下所示:
{
"version": "5",
"ws_version": "5",
"user": "XXXX",
"fields": [
{
"crm_attribute": "PREFECTURE_CODE",
"sp_attribute": "PREFECTURE_CODE",
"process_type": "field",
"in_data_type": "String",
"out_data_type": "String",
"array": "0",
"default_value": ""
},
{
"crm_attribute": "EDUCATION_LEVEL",
"sp_attribute": "EDUCATION_LEVEL",
"process_type": "field",
"in_data_type": "String",
"out_data_type": "String",
"array": "0",
"default_value": ""
}
]
}
我正在尝试更新字段数组中各个项目的属性。到目前为止我收到了这个查询:
UPDATE schema_repo sr
SET sr.sr_schema = JSON_SET(
sr.sr_schema,
'$.fields',
JSON_ARRAYAGG(
JSON_OBJECT(
'array', JSON_UNQUOTE(JSON_EXTRACT(field.value, '$.array')),
'crm_attribute', TRIM(BOTH ' ' FROM JSON_UNQUOTE(JSON_EXTRACT(field.value, '$.crm_attribute'))),
'default_value', JSON_UNQUOTE(JSON_EXTRACT(field.value, '$.default_value')),
'in_data_type', JSON_UNQUOTE(JSON_EXTRACT(field.value, '$.in_data_type')),
'out_data_type', JSON_UNQUOTE(JSON_EXTRACT(field.value, '$.out_data_type')),
'process_type', JSON_UNQUOTE(JSON_EXTRACT(field.value, '$.process_type')),
'sp_attribute', TRIM(BOTH ' ' FROM JSON_UNQUOTE(JSON_EXTRACT(field.value, '$.sp_attribute')))
)
)
), JSON_TABLE(
sr.sr_schema,
'$.fields[*]' COLUMNS (
value JSON PATH '$'
)
) AS field;
但是这里的语法不太正确。正确的没有收到此错误:
SQL Error [1064] [42000]: (conn=8976) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(
sr.sr_schema,
'$.fields[*]' COLUMNS (
value JSON PATH '$...' at line 16
我不知道如何使用
JSON_TABLE()
来更新数据。我在文档中也找不到任何内容,所有示例都用于 SELECT
查询。
这是可以做的事吗?
Json 表是一个源,必须位于 FROM 子句中
所以你的查询看起来像这样
UPDATE schema_repo sr
SET sr.sr_schema = (
SELECT JSON_SET(
sr1.sr_schema,
'$.fields',
JSON_ARRAYAGG(
JSON_OBJECT(
'array', JSON_UNQUOTE(JSON_EXTRACT(field.value, '$.array')),
'crm_attribute', TRIM(BOTH ' ' FROM JSON_UNQUOTE(JSON_EXTRACT(field.value, '$.crm_attribute'))),
'default_value', JSON_UNQUOTE(JSON_EXTRACT(field.value, '$.default_value')),
'in_data_type', JSON_UNQUOTE(JSON_EXTRACT(field.value, '$.in_data_type')),
'out_data_type', JSON_UNQUOTE(JSON_EXTRACT(field.value, '$.out_data_type')),
'process_type', JSON_UNQUOTE(JSON_EXTRACT(field.value, '$.process_type')),
'sp_attribute', TRIM(BOTH ' ' FROM JSON_UNQUOTE(JSON_EXTRACT(field.value, '$.sp_attribute')))
)
)
) FROM schema_repo sr1, JSON_TABLE(
sr1.sr_schema,
'$.fields[*]' COLUMNS (
value JSON PATH '$'
)
) AS field
WHERE sr1.sr_schema = sr.sr_schema);