更新 JSON_ARRAY Mysql 8.0 中的字段
Updating the Fields in the JSON_ARRAY Mysql 8.0
这是我的方案,我想将 BOB
的 hourly_rate 更新为 600。如何从下面提到的 json_array 中提取 hourly_rate特定用户 BOB
.
@data = [{
"Subject": "Maths",
"type": "paid",
"tutor": "MARY",
"hourly_rate": "500"
},
{
"Subject": "Maths",
"type": "paid",
"tutor": "BOB",
"hourly_rate": "700"
}]
我可以使用 JSON_SEARCH()
通过 Where
子句获取索引吗?
示例:
"Select JSON_SET(@data,'$[*].hourly_rate', 600) Where 'Subject' = Maths and 'tutor' = 'BOB'";
我成功了。但是我不得不使用 view
以获得更清晰的代码。
我的回答是基于这个:
更新查询
Fiddle@https://www.db-fiddle.com/f/7MnPYEJW2uiGYaPhSSjtKa/1
UPDATE test
INNER JOIN getJsonArray ON getJsonArray.tutor = 'BOB'
SET test =
JSON_REPLACE(
test,
CONCAT('$[', getJsonArray.rowid - 1, '].hourly_rate'), 600);
select * from test;
Ddl
CREATE TABLE `test` (
`test` json DEFAULT NULL
);
INSERT INTO `test` (`test`)
VALUES ('[{
"Subject": "Maths",
"type": "paid",
"tutor": "MARY",
"hourly_rate": "500"
},
{
"Subject": "Maths",
"type": "paid",
"tutor": "BOB",
"hourly_rate": "700"
}]');
create view getJsonArray as
select data.*
from test, json_table(
test,
"$[*]"
COLUMNS(
rowid FOR ORDINALITY,
Subject VARCHAR(100) PATH "$.Subject" DEFAULT '111' ON EMPTY DEFAULT '999' ON ERROR,
type VARCHAR(100) PATH "$.type" DEFAULT '111' ON EMPTY DEFAULT '999' ON ERROR,
tutor VARCHAR(100) PATH "$.tutor" DEFAULT '111' ON EMPTY DEFAULT '999' ON ERROR,
hourly_rate JSON PATH "$.hourly_rate" DEFAULT '{"x": 333}' ON EMPTY
)
) data
;
这是我的方案,我想将 BOB
的 hourly_rate 更新为 600。如何从下面提到的 json_array 中提取 hourly_rate特定用户 BOB
.
@data = [{
"Subject": "Maths",
"type": "paid",
"tutor": "MARY",
"hourly_rate": "500"
},
{
"Subject": "Maths",
"type": "paid",
"tutor": "BOB",
"hourly_rate": "700"
}]
我可以使用 JSON_SEARCH()
通过 Where
子句获取索引吗?
示例:
"Select JSON_SET(@data,'$[*].hourly_rate', 600) Where 'Subject' = Maths and 'tutor' = 'BOB'";
我成功了。但是我不得不使用 view
以获得更清晰的代码。
我的回答是基于这个:
更新查询
Fiddle@https://www.db-fiddle.com/f/7MnPYEJW2uiGYaPhSSjtKa/1
UPDATE test
INNER JOIN getJsonArray ON getJsonArray.tutor = 'BOB'
SET test =
JSON_REPLACE(
test,
CONCAT('$[', getJsonArray.rowid - 1, '].hourly_rate'), 600);
select * from test;
Ddl
CREATE TABLE `test` (
`test` json DEFAULT NULL
);
INSERT INTO `test` (`test`)
VALUES ('[{
"Subject": "Maths",
"type": "paid",
"tutor": "MARY",
"hourly_rate": "500"
},
{
"Subject": "Maths",
"type": "paid",
"tutor": "BOB",
"hourly_rate": "700"
}]');
create view getJsonArray as
select data.*
from test, json_table(
test,
"$[*]"
COLUMNS(
rowid FOR ORDINALITY,
Subject VARCHAR(100) PATH "$.Subject" DEFAULT '111' ON EMPTY DEFAULT '999' ON ERROR,
type VARCHAR(100) PATH "$.type" DEFAULT '111' ON EMPTY DEFAULT '999' ON ERROR,
tutor VARCHAR(100) PATH "$.tutor" DEFAULT '111' ON EMPTY DEFAULT '999' ON ERROR,
hourly_rate JSON PATH "$.hourly_rate" DEFAULT '{"x": 333}' ON EMPTY
)
) data
;