源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2021-11-10 14:08 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:简单谈谈MySQL5.7 JSON格式检索
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类列的数据 [code]select json_extract(content,  '$.name' )  from json_test  where json_extract(content,  '$.name' )= "zhangsan" ;[/code] 通过expain分析改查询语句,发现其走全表扫描 [img]http://files.jb51.net/file_images/article/201701/201701011423551.jpg[/img] 在网上查询资料,得知如果要在JSON列上进行检索,需要对检索的key创建虚拟列,然后再虚拟列上创建索引 第四步:在content列上,对"name"建立虚拟列 [code]ALTER TABLE json_test  ADD name_virtual  varchar (32) GENERATED ALWAYS  AS (json_extract(content,  '$.name' )) VIRTUAL; [/code] 第五步:对虚拟列创建索引 [code]CREATE INDEX name_virtual_index  ON json_test(name_virtual); [/code] 再次做查询( 注,where条件需要使用虚拟列来进行检索,如果直接用JSON列比较,还是会走全表扫描 ) [code]explain  select json_extract(content,  '$.name' )  from json_test  where name_virtual= "zhangsan" \G[/code] [img]http://files.jb51.net/file_images/article/201701/201701011423552.jpg[/img] 总结: 其实MySQL通过一种空间换时间的做法,类似创建一个触发器,把JSON列上的数据冗余存储到虚拟列上,比较的时候通过走虚拟列的索引,再定位到实际数据。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部