MySQL 提供了丰富的函数用于 JSON 类型字段的查找与更新,详见官方文档。
CREATE TABLE `t1` (`id` int(11) NOT NULL AUTO_INCREMENT,`basic_info` json DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `t1`(`id`, `basic_info`)
VALUES (1, '{\"age\": 9, \"name\": \"小明\", \"class\": 3}');
比如查询 id=1 的 basic_info 中的 name 字段,可以用以下两种方式:
select basic_info->'$.name' from t1 where id =1;
//或者
select JSON_EXTRACT(basic_info, '$.name') from t1 where id =1;
比如查询name为小明的记录:
select * from t1 where basic_info->'$.name' = '小明';
//或者
select * from t1 where JSON_EXTRACT(basic_info,'$.name') = '小明';
检索JSON数据的方法,文档:https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html
比如我们修改 id =1 的 basic_info 中的age为 10 岁:
可以使用JSON_REPLACE() 或者 JSON_SET() 函数:
update t1 set basic_info = JSON_REPLACE(basic_info, '$.age', 10) where id =1;
//或者
update t1 set basic_info = JSON_SET(basic_info, '$.age', 10) where id =1;
比如往 basic_info 中插入一个性别“gender”字段:
可以使用JSON_INSERT() 或者 JSON_SET() 函数:
update t1 set basic_info = JSON_INSERT(basic_info, '$.gender', '男')
where id =1;
//或者
update t1 set basic_info = JSON_SET(basic_info, '$.gender', '男')
where id =1;
SON_SET(),JSON_INSERT() 和JSON_REPLACE() 函数的区别:
JSON_SET() 支持替换现有值,并且支持添加不存在的值。
JSON_INSERT() 插入值而不替换现有值。
JSON_REPLACE() 仅替换现有值。