当前位置:   article > 正文

MySQL JSON类型字段的查找与更新_mysql json update

mysql json update


MySQL 提供了丰富的函数用于 JSON 类型字段的查找与更新,详见官方文档。

创建一个表 t1,basic_info 字段为JSON类型:

  1. CREATE TABLE `t1` (
  2.   `id` int(11) NOT NULL AUTO_INCREMENT,
  3.   `basic_info` json DEFAULT NULL,
  4.   PRIMARY KEY (`id`)
  5. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


插入一条数据:

  1. INSERT INTO `t1`(`id`, `basic_info`)
  2. VALUES (1, '{\"age\": 9, \"name\": \"小明\", \"class\": 3}');


一、检索 JSON:
1、查找 JSON 中的某个字段:

比如查询 id=1 的 basic_info 中的 name 字段,可以用以下两种方式:

  1. select basic_info->'$.name' from t1 where id =1;
  2. //或者
  3. select JSON_EXTRACT(basic_info, '$.name') from t1 where id =1;


2、根据JSON中的某个字段查询表中记录:

比如查询name为小明的记录:

  1. select * from t1 where basic_info->'$.name' = '小明'
  2. //或者 
  3. select * from t1 where JSON_EXTRACT(basic_info,'$.name') = '小明';


检索JSON数据的方法,文档:https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html

二、修改 JSON

1、修改 JSON 中的某个字段:

比如我们修改 id =1 的 basic_info 中的age为 10 岁:

可以使用JSON_REPLACE() 或者 JSON_SET() 函数:

  1. update t1 set basic_info = JSON_REPLACE(basic_info, '$.age', 10) where id =1
  2. //或者 
  3. update t1 set basic_info = JSON_SET(basic_info, '$.age', 10) where id =1;


2、往 JSON 中插入一个新的字段:

比如往 basic_info 中插入一个性别“gender”字段:

可以使用JSON_INSERT() 或者 JSON_SET() 函数:

  1. update t1 set basic_info = JSON_INSERT(basic_info, '$.gender', '男')
  2. where id =1
  3. //或者 
  4. update t1 set basic_info = JSON_SET(basic_info, '$.gender', '男')
  5. where id =1;


SON_SET(),JSON_INSERT() 和JSON_REPLACE() 函数的区别:

JSON_SET() 支持替换现有值,并且支持添加不存在的值。

JSON_INSERT() 插入值而不替换现有值。

JSON_REPLACE() 仅替换现有值。
 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/297058
推荐阅读
相关标签
  

闽ICP备14008679号