mysql json类型

参考了https://www.cnblogs.com/captainad/p/11176127.html, 

最近查数据库时,遇到了下面这样的,

 select 字段名 from 表 where data='{}'怎么都查不出来 ,突然注意到它的字段类型原来是json类型。

json 数据类型是mysql 5.7之后引入的 

新建:json类型创建和其他类型差不多,跳过.

插入:INSERT into Student(content) VALUES ('{"name":"zhangsan","age":22}');

更新:update Student set content = '{"name":"xiaoming","age":19,"height":"1.82"}' where id =2 ; 更新也差不多

增加json数据类型的好处:

1.保证了JSON数据类型的强校验、

2。MySQL同时提供了一组操作JSON类型数据的内置函数、

3。更优化的存储格式 ,容易读取

4。基于json格式的特征支持修改特定的值

常用json函数:

 查询sql :查询json中某个字段值 

 使用 字段->’$.json属性’进行查询条件

或者JSON_EXTRACT(字段, "$.json属性")

  select  * from student where content->'$.name' = "zhangsan"; 

select content->"$.name" from student where id =2;

select JSON_EXTRACT(content, "$.name") from student where id =2;

json_keys 查询json中含有的所有属性名,并返回数组

SELECT id,json_keys(content) FROM student;

json_set 增加json中属性

UPDATE student SET content = json_set(content,'$.weight','105') WHERE id = 2;

 json_replace 替换

JSON_DEPTH 深度 

json_length 长度  

 select  JSON_LENGTH(content) from student ;

{"age": 22, "name": "zhangsan"} 2

{"age": 19, "name": "xiaoming", "height": "1.82", "weight": "105"}  4

 select  JSON_DEPTH (content) from student ;  

{"age": 22, "name": "zhangsan"} 2

{"age": 19, "name": "xiaoming", "height": "1.82", "weight": "105"}  2

原文地址:https://www.cnblogs.com/yxj808/p/14981133.html