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)
相关推荐
倔强的石头_1 分钟前
【金仓数据库】ksql 指南(七) —— 启动和管理事务(KingbaseES 数据一致性保障)
数据库
计算机毕设vx_bysj686917 分钟前
计算机毕业设计必看必学~基于SpringBoot校园招聘系统的设计与实现,原创定制程序、单片机、java、PHP、Python、小程序、文案全套、毕设成品等!
java·spring boot·mysql·课程设计
志栋智能24 分钟前
自动化运维真的只能选复杂平台吗?
运维·网络·数据库·人工智能·自动化
LaughingZhu34 分钟前
Product Hunt 每日热榜 | 2026-02-17
大数据·数据库·人工智能·经验分享·搜索引擎
树码小子1 小时前
Mybatis(16)Mybatis-Plus条件构造器(1)
数据库·mybatis-plus
翔云1234561 小时前
在MySQL中,出现Executed_Gtid_Set 乱序增长的场景
数据库·mysql
志栋智能2 小时前
AI驱动的数据库自动化巡检:捍卫数据王国的“智能中枢”
大数据·运维·数据库·人工智能·云原生·自动化
Ama_tor2 小时前
Navicat|简介,安装与MySQL连接
数据库·navicat
程序员林北北3 小时前
【前端进阶之旅】一种新的数据格式:TOON
前端·javascript·vue.js·react.js·typescript·json
l1t3 小时前
DeepSeek辅助生成的PostgreSQL 查询优化实战幻灯片脚本
大数据·数据库·postgresql