mysql5.7以上支持json的操作,以及增加了json存储类型
一般数据库存储json类型的数据会用json类型或者text类型
注意:用json类型的话
1)JSON列存储的必须是JSON格式数据,否则会报错。
2)JSON数据类型是没有默认值的。
查询根据表字段的json内容进行查询
- 首先创建表
create table log( id int not null, content varchar(255), createTime TIMESTAMP, data text )
- 插入几个测试数据
- 执行查询sql
使用 字段->’$.json属性’进行查询条件
select * from log where data->'$.id' = 142;
或
select data->'$.id' id,data->'$.name' name from log where data->'$.id' = 142;
测试根据json数组的字段查询
1.再建一个表log2,插入几条json数组数据
[{ "id": "141", "name": "xxx", "type": "input" }, { "id": "142", "name": "xin", "type": "textarea" } ]
查询json数组里面对象的id等于142的记录
用JSON_CONTAINS(字段,JSON_OBJECT(‘json属性’, “内容”))
select * from log2 where JSON_CONTAINS(data,JSON_OBJECT('id', "142"))
搬运自:https://www.codetd.com/article/7994664