1、json对象
1.1、方法
- 使用对象操作的方法进行查询:
字段->'$.json属性' - 使用函数进行查询:
json_extract(字段, '$.json属性') - 获取json数组/对象长度:
json_length()
1.2、数据
create table `test` (
`id` bigint(20) unsigned not null auto_increment comment '自增id',
`goods_sn` varchar(25) not null default '' comment '商品编码',
`desc_attr` json not null comment '描述属性',
primary key (`id`)
) engine=innodb comment='test';
insert into `test`.`test`(`id`, `goods_sn`, `desc_attr`) values (1, 'a0001', '{\"tag\": [\"grs\", \"gots\"], \"size\": \"m\", \"color\": \"红色\", \"material\": \"尼龙\"}');
insert into `test`.`test`(`id`, `goods_sn`, `desc_attr`) values (2, 'a0002', '{\"tag\": [\"grs\", \"gots\", \"mtd\"], \"size\": \"la\", \"color\": \"黄色\", \"material\": \"纯棉\"}');1.3、查询
-- 查询面料不为空的商品 select * from test where desc_attr->'$.material' is not null; select * from test where json_extract(desc_attr, '$.material') is not null; -- 查询面料为纯棉的商品 select * from test where desc_attr->'$.material'='纯棉'; select * from test where json_extract(desc_attr, '$.material')='纯棉'; -- 查询标签数量大于2的商品 select * from test where json_length(desc_attr->'$.tag')>2;
2、json数组
2.1、方法
- 对象操作方式查询:
字段->'$[*].属性' - 使用函数查询:
json_contains(字段,json_object('json属性', '内容')) - 获取json数组/对象长度:
json_length()
2.2、数据
create table `test2` (
`id` bigint(20) unsigned not null auto_increment comment '自增id',
`goods_sn` varchar(25) not null default '' comment '商品编码',
`desc_attrs` json not null comment '描述属性,多个',
primary key (`id`)
) engine=innodb comment='test2';
insert into `test`.`test2`(`id`, `goods_sn`, `desc_attrs`) values (1, 'a0001', '[{\"tag\": [\"grs\", \"gots\"], \"size\": \"m\", \"color\": \"红色\", \"material\": \"尼龙\"}, {\"tag\": [\"grs\", \"gots\", \"mtd\"], \"size\": \"la\", \"color\": \"黄色\", \"material\": \"纯棉\"}]');
insert into `test`.`test2`(`id`, `goods_sn`, `desc_attrs`) values (2, 'a0002', '[{\"tag\": [\"grs\", \"gots\"], \"size\": \"m\", \"color\": \"红色\", \"material\": \"尼龙\"}, {\"tag\": [\"grs\", \"gots\", \"mtd\"], \"link\": \"xxx\", \"size\": \"la\", \"color\": \"黄色\", \"material\": \"纯棉\"}]');
insert into `test`.`test2`(`id`, `goods_sn`, `desc_attrs`) values (3, 'a0003', '[]');2.3、查询
-- 查询描述属性不为空的商品
select * from test2 where json_length(desc_attrs) > 0;
-- 查询第1项存在颜色属性的商品
select * from test2 where desc_attrs->'$[0].color' is not null;
-- 查询任意项存在链接属性的商品
select * from test2 where desc_attrs->'$[*].link' is not null;
-- 查询任意项存在链接等于xxx属性的商品
select * from test2 where json_contains(desc_attrs,json_object('link', 'xxx'));注意
-- [{"link":"xxx"}]
select desc_attrs->'$[*].link' from test2 where id=2;
-- 查询结果为`["xxx"]`
-- 返回每一项的link,所以是个数组到此这篇关于mysql json类型数据查询的文章就介绍到这了,更多相关mysql json类型数据查询内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论