当前位置: 移动技术网 > IT编程>数据库>Mysql > 简单谈谈MySQL5.7 JSON格式检索

简单谈谈MySQL5.7 JSON格式检索

2017年12月12日  | 移动技术网IT编程  | 我要评论

mysql5.7版本开始支持json格式,在创建表时,可以指定列表的数据类型为json,但是如何在json格式上创建索引呢??

本人做了一个简单测试。

第一步:建立一个包含json类型的表:

create table json_test` (
 id` int (8) not null auto_increment,
 content` json not null ,
 primary key (`id`)
) engine=innodb default charset=utf8;

第二步:初始化数据

insert into json_test(content) value( '{"name":"zhangsan","age":18}' );
insert into json_test(content) value( '{"name":"lisi","age":19}' );
insert into json_test(content) value( '{"name":"wangwu","age":20}' );

第三步:查询json类列的数据

select json_extract(content,  '$.name' )  from json_test  where json_extract(content,  '$.name' )= "zhangsan" ;

通过expain分析改查询语句,发现其走全表扫描

在网上查询资料,得知如果要在json列上进行检索,需要对检索的key创建虚拟列,然后再虚拟列上创建索引

第四步:在content列上,对"name"建立虚拟列

alter table json_test  add name_virtual  varchar (32) generated always  as (json_extract(content,  '$.name' )) virtual;

第五步:对虚拟列创建索引

create index name_virtual_index  on json_test(name_virtual);

再次做查询( 注,where条件需要使用虚拟列来进行检索,如果直接用json列比较,还是会走全表扫描 )

explain  select json_extract(content,  '$.name' )  from json_test  where name_virtual= "zhangsan" \g

总结:

其实mysql通过一种空间换时间的做法,类似创建一个触发器,把json列上的数据冗余存储到虚拟列上,比较的时候通过走虚拟列的索引,再定位到实际数据。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网