函数:JSON_EXTRACT(json字段列名,"$.json属性名")
Mysql中表设计中某些预留字段,可扩展字段json字段,json中属性获取函数:
select JSON_EXTRACT(json字段的名称,"$.json的属性1") as '别名' from db_name;
举例:
CREATE TABLE `student` (
`sid` varchar(100) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`expand` json DEFAULT NULL,
PRIMARY KEY (`sid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Student'
插入数据:
INSERT INTO amall_crawler.student (sid,name,expand) VALUES
('1001','xiaoliu','{"sex": "man", "hobby": ["游泳", "打乒乓"], "address": {"detail": "某某小区某某栋0001", "city": "某某市"}}');
1) 单层属性值获取---获取expand的json字段中sex属性的值:
JSON_EXTRACT(字段名,"$.json属性名")
2) 多层属性值获取---获取expand的json字段中address属性下detail属性的值:
JSON_EXTRACT(JSON_EXTRACT(字段名,"$.json属性名1"),"$.json属性名2")
select
name,
JSON_EXTRACT(expand,
"$.sex") as 'sex',
JSON_EXTRACT(JSON_EXTRACT(expand, "$.address"),
"$.detail") as 'addressDetail'
student;
使用JSON_EXTRACT查出的json串中String类型的属性值,会带双引号,可以用replace函数将其替换掉
3) json字段的属性作为查询条件时,查询方式:
查询出sex = man的数据
select * from student where JSON_EXTRACT(expand,"$.sex") = 'man';