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.14(java)4 分钟前
MySQL索引原理与B+树应用详解
数据库·b树·mysql
java干货5 分钟前
用 MySQL SELECT SLEEP() 优雅模拟网络超时与并发死锁
网络·数据库·mysql
哈哈不让取名字7 分钟前
使用Fabric自动化你的部署流程
jvm·数据库·python
洛_尘9 分钟前
MySQL 6:数据库约束
数据库·mysql
dawudayudaxue10 分钟前
sqlite在安卓下使用ndk的交叉编译
android·数据库·sqlite
YIN_尹10 分钟前
【MySQL】表的约束(下)
android·数据库·mysql
lkbhua莱克瓦2413 分钟前
Apache Maven全面解析
java·数据库·笔记·maven·apache
optimistic_chen14 分钟前
【Redis系列】哨兵模式
linux·数据库·redis·分布式·哨兵
啊吧怪不啊吧24 分钟前
极致性能的服务器Redis之Hash类型及相关指令介绍
大数据·数据库·redis·sql·mybatis·哈希算法
五阿哥永琪33 分钟前
MySQL面试题 如何解决深分页?
数据库·mysql