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)
相关推荐
SelectDB9 小时前
阶跃星辰基于 SelectDB 构建 PB 级 Agent 可观测平台
大数据·数据库·aigc
这个DBA有点耶10 小时前
GROUP BY优化全解:如何写出既不丢数据又飞快的分组查询
数据库·mysql·架构
掉头发的王富贵13 小时前
【StarRocks】极限十分钟入门StarRocks
数据库·sql·mysql
Nturmoils13 小时前
WHERE 条件别凭习惯写,常用查询先跑一遍
数据库
SamDeepThinking18 小时前
一条UPDATE语句在MySQL 8.0中到底加了几把锁?
后端·mysql·程序员
Databend1 天前
在 AWS 中国峰会逛了一天,我在 Databend 展台看到了 Agent 数据基础设施的新思路
数据库·人工智能·agent
李白客3 天前
KES新版MySQL兼容能力再升级意味着什么?
mysql·国产数据库
ClouGence3 天前
Oracle 数据同步为什么会出现数据不一致?长事务是常被忽略的原因
数据库·后端·oracle
飞将3 天前
从零实现数据库(2)——HashIndex + IndexManager
数据库
Nturmoils4 天前
订单列表慢查询,先看 WHERE、ORDER BY 和 LIMIT
数据库