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)
相关推荐
2401_8654396337 分钟前
HTML函数在低温环境下启动慢吗_温度对硬件启动影响【方法】
jvm·数据库·python
NotFound48641 分钟前
分享实战心得PostgreSQL 主从复制:告别单点故障,附主从切换与延迟监控命令
数据库·postgresql
minebmw77 小时前
Oracle 19.29 中 ORA-00600 [4193] 错误完全解析与恢复指南
数据库·oracle
m0_377618237 小时前
Golang怎么连接MySQL数据库_Golang MySQL连接教程【总结】
jvm·数据库·python
weixin_586061468 小时前
C#怎么通过反射获取类属性_C#如何动态读取元数据【进阶】
jvm·数据库·python
Pluto_CSND8 小时前
PostgreSQL 聚合函数总览
数据库·postgresql
资深数据库专家8 小时前
总账EBS 应用服务器1 的监控分析
java·网络·数据库
m0_678485459 小时前
CSS如何控制表格单元格边框合并_通过border-collapse实现
jvm·数据库·python
m0_748839499 小时前
如何用组合继承模式实现父类方法复用与子类属性独立
jvm·数据库·python
qq_334563559 小时前
PHP源码是否依赖特定芯片组_Intel与AMD平台差异【操作】
jvm·数据库·python