MySQL json字段索引添加及使用

在业务系统中,由于上级接口的变化,我们需要不断的在一张特别大的表上新增字段、同时修改源码。为了后续新增字段方便,我们在表上添加了一列 extra_config,用来存储后续添加的字段

  • 建表
sql 复制代码
create table outer_order
(
    id           bigint primary key auto_increment,
    extra_config json,
    create_time  datetime(3) DEFAULT CURRENT_TIMESTAMP(3),
    update_time  datetime(3) default null ON UPDATE CURRENT_TIMESTAMP(3)
);
  • 插入数据
sql 复制代码
insert into outer_order (extra_config)
values ('{"zipcode":"430101","price": 1.92, "quantity": 1, "alias_array":  [1,3]}'),
       ('{"zipcode":"430102","price": 2.92, "quantity": 2, "alias_array":  [2,3]}'),
       ('{"zipcode":"430103","price": 3.92, "quantity": 3, "alias_array":  [4,3]}'),
       ('{"zipcode":"430104","price": 4.92, "quantity": 4, "alias_array":  [5,3]}'),
       ('{"zipcode":"430105","price": 5.92, "quantity": 5, "alias_array":  [6,3]}'),
       ('{"zipcode":"430106","price": 6.92, "quantity": 6, "alias_array":  [7,3]}'),
       ('{"zipcode":"430107","price": 7.92, "quantity": 7, "alias_array":  [8,3]}'),
       ('{"zipcode":"430107","price": 8.92, "quantity": 8, "alias_array":  [9,3]}')
;
  • 添加虚拟列
sql 复制代码
alter table outer_order add column extra_config_price decimal(11,2) generated always as (extra_config->>'$.price') not null;
  • 添加索引
sql 复制代码
alter table outer_order add index idx_vm_extra_config_price (extra_config_price);
  • 使用索引
sql 复制代码
explain select id from outer_order where extra_config_price = 1.92;

结果如下

复制代码
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: outer_order
   partitions: NULL
         type: ref
possible_keys: idx_vm_extra_config_price
          key: idx_vm_extra_config_price
      key_len: 5
          ref: const
         rows: 1
     filtered: 100.00
        Extra: Using index
1 row in set, 1 warning (0.00 sec)
相关推荐
雲烟14 分钟前
Qt SQLite在I.mx8上使用问题
数据库·qt·i.mx8
合作小小程序员小小店35 分钟前
web开发,在线%药店管理%系统,基于Idea,html,css,jQuery,java,ssm,mysql。
java·前端·mysql·jdk·html·intellij-idea
TDengine (老段)39 分钟前
TDengine 转换函数 CAST 用户手册
java·大数据·数据库·物联网·时序数据库·tdengine·涛思数据
苦瓜炒蛋挞1 小时前
小迪安全第二十二天-安全开发-PHP应用&数据库操作&留言板功能&第三方插件
数据库·网络安全·php·小迪安全
chushiyunen1 小时前
redis命令 geo(对地理坐标的支持)
数据库·redis·缓存
baivfhpwxf20231 小时前
删除数据表SQL,不是删除数据,是删除表结构
数据库·sql
码界奇点2 小时前
深入解析MySQL6存储过程游标与触发器的实战应用与性能优化
数据库·sql·性能优化·七牛云存储
数据知道2 小时前
FastAPI项目:从零到一搭建一个网站导航系统
python·mysql·fastapi·python web·python项目
鸽鸽程序猿2 小时前
【Redis】List类型介绍
数据库·redis·list
帅中的小灰灰2 小时前
C++编程观察者设计模式
数据库·c++·设计模式