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)
相关推荐
为思念酝酿的痛3 小时前
MySQL数据类型
数据库·mysql
泡海椒3 小时前
JQuick-SQL 与关系型数据库集成:应用层读取后注册查询
数据库·sql
Carol06303 小时前
上肢及肩肘关节
java·服务器·数据库
程序员塔塔喵4 小时前
【MySQL篇|第二篇】慢SQL及其优化手段
sql·mysql·慢sql优化
鸽芷咕4 小时前
数据孤岛怎么拆?金仓KFS数据集成软件从原理到落地
数据库
一世繁华行4 小时前
CAPL浏览器(翻译自官方文档)
运维·服务器·数据库
得助智能-垂类大模型4 小时前
多Agent平台哪家做得好?2026年企业级多智能体平台选型指南
大数据·数据库
为思念酝酿的痛4 小时前
MySQL数据库基础
数据库·mysql
瀚高PG实验室5 小时前
数据库使用psql及jdbc进行远程连接,不定时自动断开的解决办法
数据库·postgresql·瀚高数据库
SelectDB技术团队5 小时前
从实时入库到实时可用:Apache Doris 5.0 增量计算场景与实践
数据库·人工智能·开源·agent·实时数仓·apache doris·增量计算