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类型数据查询内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

声明:本站(华域联盟www.cnhackhy.com)所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。