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)
相关推荐
Nturmoils几秒前
集中式与分布式怎么选:从订单读写看 KingbaseES 的架构边界
数据库
xiaomuzuirenzhen9 分钟前
大专电子商务从事电商运营分析师需要考证吗?
大数据·数据库
翔云1234562 小时前
RocksDB中,客户端每写入一次数据,需要访问几次磁盘
运维·数据库·mysql
DevOpenClub3 小时前
职教高考控制线 API:招生类别枚举、筛选与空分数含义
java·数据库·高考
GeW4 小时前
新质生产力路线图解读:数据库性能优化与Linux调优专场
linux·数据库
在多学一点6 小时前
MYSQL第二次作业
android·数据库·mysql
yeccheng6 小时前
MySQL 索引超详解:从底层 B+ 树到面试高频考点
java·开发语言·jvm·mysql·面试
Risehuxyc6 小时前
Microsoft.Data.Sqlite体验
数据库·sqlite
骑着蜗牛撵大象3276 小时前
MySQL 8.0 迁移后 SQL 变慢:执行计划里 3 类被忽略的成本差异
android·数据库·sql·mysql·优化器·执行计划
ZENERGY-众壹7 小时前
告警风暴怎么压?100MW 电站监控平台告警引擎架构复盘
数据库·架构·iot·电站监控