MySQL 8.0新特性 -- 不可见索引

时间:2020-04-01
本文章向大家介绍MySQL 8.0新特性 -- 不可见索引,主要包括MySQL 8.0新特性 -- 不可见索引使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

MySQL支持不可见索引,即优化器不会使用该索引。
不可见索引特性不可以用于主键。

默认索引是可见的。可以在create table、create index、alter table操作中使用关键字visible、invisible来指定索引是否可见。

create table t1 (
  i int,
  j int,
  k int,
  index i_idx (i) invisible
) engine = innodb;
create index j_idx on t1 (j) invisible;
alter table t1 add index k_idx (k) invisible;

修改已经存在的索引的可见性:

alter table t1 alter index i_idx invisible;
alter table t1 alter index i_idx visible;

  

可以通过information_schema.statistics、show index查看索引的可见性:

>select index_name, is_visible
-> from information_schema.statistics
-> where table_schema = 'abce' and table_name = 't1';
+------------+------------+
| INDEX_NAME | IS_VISIBLE |
+------------+------------+
| i_idx      | NO         |
+------------+------------+
1 row in set (0.00 sec)

>show index from t1;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| t1    |          1 | i_idx    |            1 | i           | A         |           0 |     NULL |   NULL | YES  | BTREE      |         |               | NO      | NULL       |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
1 row in set (0.00 sec)

不可见索引可以用来测试移除索引后对查询性能的影响。毕竟对于大表,删除和重建索引是非常昂贵的操作。
系统变量optimizer_switch中的use_invisible_indexes标志控制了优化器是否使用不可见索引来构建执行计划。
如果use_invisible_indexes=off(默认设置),优化器会忽略不可见索引;如果设置为on,索引仍然不可见,但是优化器在生成执行计划的时候会考虑不可见索引。

原文地址:https://www.cnblogs.com/abclife/p/12613964.html