Mysql JSON 更新键值

Mysql JSON update key value

我有一个 table 喜欢:

CREATE TABLE `campus_tb` (
 `campus_id` int(11) NOT NULL AUTO_INCREMENT,
 `campus_dataJSON` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL CHECK (json_valid(`campus_dataJSON`)),
 PRIMARY KEY (`campus_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

INSERT INTO `campus_tb`( `campus_dataJSON`) VALUES ( '[
                          {"id":"100","name":"James","age":"17","course":"IT"},
                          {"id":"101","name":"Eric","age":"19","course":"CS"},
                          {"id":"102","name":"Julie","age":"21"}]')




+--------------------+-----------------------------------------------------------+
| campus_id          |  campus_dataJSON                                          | 
+--------------------+-----------------------------------------------------------+
| 1                  |  [
                     |     {"id":"100","name":"James","age":"17","course":"IT"},
                     |     {"id":"101","name":"Eric","age":"19","course":"CS"},
                     |     {"id":"102","name":"Julie","age":"21"}
                     |
                     |  ] 
----------------------------------------------------------------------------------  
| 2                  |  [
                     |     {"id":"34","name":"Mimi","age":"18","course":"IT"},
                     |     {"id":"35","name":"Jose","age":"20","course":"CS"},
                     |     {"id":"36","name":"Ken","age":"24"}
                     |
                     |  ]
----------------------------------------------------------------------------------  

我正在使用 MariaDB 10.4

  1. MySql 查询更新 campus_id = 1Julie 的详细信息以添加 “课程” 让她变得像:

    {"id":"102","name":"Julie","age":"21","course":"MASCOM"},

  2. Mysql 查询从 "Eric""Erick" 更新为 "k " 最后

到目前为止我已经尝试过:

UPDATE `campus_tb` 
SET `campus_dataJSON` = JSON_SET (`campus_dataJSON`, TRIM( '"' FROM JSON_SEARCH(`campus_dataJSON`,'one','Julie')),'MASCOM') 
WHERE 
    `campus_id` = 1 AND 
    JSON_EXTRACT(`campus_dataJSON`,'$.id') = '102';

这个returns 0 rows affected...我用谷歌搜索了很多。

基本上你应该使用JSON_SET函数。例如第一个问题可以通过以下方式解决:

update campus 
 set campus_data = json_set(
   campus_data, '$[2].course', 'MASCOM')
 where campus_id = 1;

测试SQLize.online

如果您不知道 JSON 路径,您可以使用 JSON_SEARCH & JSON_UNQUOTE,例如:

update campus 
 set campus_data = json_set(
   campus_data, 
   json_unquote(json_search(campus_data, 'one', 'Eric')), 
   'Erick'
 )
 where campus_id = 1;
 

Fiddle here