创建 JSON
类似 varchar,设置 JSON 主要将字段的 type 是 json, 不能设置长度,可以是 NULL 但不能有默认值。
data
json
插入 JSON
INSERT INTO `test` (data) VALUES ('{"name":"tom","age":3}');
查询 JSON
查询 json 中的数据用 column->path 的形式,其中对象类型 path 这样表示 $.path, 而数组类型则是 $[index]
select data->'$.name',data->'$.age' from test where id = 1;
// "tom" | 3
可以看到对应字符串类型的 category->’$.name’ 中还包含着双引号,这其实并不是想要的结果,可以用 JSON_UNQUOTE 函数将双引号去掉,从 MySQL 5.7.13 起也可以通过这个操作符 ->> 这个和 JSON_UNQUOTE 是等价的
更新
- JSON_INSERT() 插入新值,但不会覆盖已经存在的值 (可以插入多个)
update test set data = JSON_INSERT(data,'$.kind','cat','$.color','blue') where id = 1;
- JSON_SET() 插入新值,并覆盖已经存在的值
update test set data = JSON_SET(data,'$.kind','mouse','$.color','grey','$.favorite','meat') where id = 1;
- JSON_REPLACE() 只替换存在的值
update test set data = JSON_REPLACE(data,'$.kind','mouse','$.color','grey','$.favorite','meat') where id = 1;
删除
JSON_REMOVE() 删除 JSON 元素
update test set data = JSON_REMOVE(data,'$.kind','mouse','$.color','grey','$.favorite','meat') where id = 1;
注:如若 json 的 key 中有特殊字符可以使用 「"」包裹:'$."a-b"'