繁体   English   中英

更新 JSON_ARRAY Mysql 8.0 中的字段

[英]Updating the Fields in the JSON_ARRAY Mysql 8.0

这是我的场景,我想将BOB的 hourly_rate 更新为 600。如何从下面提到的特定用户BOB的 json_array 中提取 hourly_rate。

@data = [{
 "Subject": "Maths",
 "type": "paid",
 "tutor": "MARY",
 "hourly_rate": "500"
},
{
 "Subject": "Maths",
 "type": "paid",
 "tutor": "BOB",
 "hourly_rate": "700"
}]

我可以使用JSON_SEARCH()通过使用Where子句来获取索引JSON_SEARCH()

例子:

  "Select JSON_SET(@data,'$[*].hourly_rate', 600) Where 'Subject' = Maths and 'tutor' = 'BOB'";

我得到了这个工作。 但是我必须使用view才能获得更清晰的代码。

我的回答基于这个: https : //stackoverflow.com/a/51563616/1688441


更新查询

小提琴@ 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;    

滴滴

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
      ;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM