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)
相关推荐
odoo中国8 分钟前
配置 Odoo 的 PostgreSQL 数据库以允许远程访问的步骤
数据库·postgresql·odoo
麓殇⊙8 分钟前
spring--事务详解
数据库·spring·oracle
鱼儿也有烦恼3 小时前
MySQL bin目录下的可执行文件
数据库·mysql
唯♧4 小时前
pg数据库删除模式
数据库·oracle
noravinsc6 小时前
django.db.models.query_utils.DeferredAttribute object
数据库·django·sqlite
阿桨9 小时前
【Prometheus-MySQL Exporter安装配置指南,开机自启】
数据库·mysql
红烧柯基9 小时前
解决redis序列号和反序列化问题
java·数据库·redis
小黄人20259 小时前
【KWDB 创作者计划】一款面向 AIoT 的多模数据库实战体验
数据库·云计算·kwdb
wangzhongyudie9 小时前
SQL实战:03之SQL中的递归查询
数据库·hive·sql
API_technology9 小时前
《淘宝 API 数据湖构建:实时商品详情入湖 + Apache Kafka 流式处理指南》
数据库·分布式·数据挖掘·kafka·apache