mysql中使用json

创建表

1
2
3
4
5
6
7
8
9
10
11
12
CREATE TABLE `dept` (
`id` int(11) NOT NULL,
`dept` varchar(255) DEFAULT NULL,
`json_value` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into dept VALUES(1,'部门1','{"deptName": "部门1", "deptId": "1", "deptLeaderId": "3"}');
insert into dept VALUES(2,'部门2','{"deptName": "部门2", "deptId": "2", "deptLeaderId": "4"}');
insert into dept VALUES(3,'部门3','{"deptName": "部门3", "deptId": "3", "deptLeaderId": "5"}');
insert into dept VALUES(4,'部门4','{"deptName": "部门4", "deptId": "4", "deptLeaderId": "5"}');
insert into dept VALUES(5,'部门5','{"deptName": "部门5", "deptId": "5", "deptLeaderId": "5"}');

使用 字段名称 -> ‘$.属性’

1
select * from dept where json_value -> '$.deptName' = '部门1'
字段名称去掉 ‘’ ->>
1
select json_value ->> '$.deptName' from dept

关联

1
SELECT * from dept,dept_leader WHERE dept.json_value->'$.deptLeaderId'=dept_leader.json_value->'$.id' ;

提取字段

1
select id,json_extract(json_value,'$.deptName') as deptName from dept;

包含

1
select * from dept WHERE JSON_CONTAINS(json_value, JSON_OBJECT("deptName","部门5"))
json_object 转成json
json_array 转成 json_array

函数JSON_KEYS() :JSON文档中的键数组

1
SELECT JSON_KEYS(json_value) FROM dept 

函数JSON_SET() :将数据插入JSON格式中,有key则替换,无key则新增

1
update dept set json_value=JSON_SET('{"deptName": "部门2", "deptId": "2", "deptLeaderId": "4"}','$.deptName','新增的部门1','$.newData','新增的数据') WHERE id=2;
作者

建指所向

发布于

2022-01-18

更新于

2023-11-07

许可协议