您好,欢迎访问一九零五行业门户网

MySQL中B+树索引的管理

目前mysql数据库存在的一个普遍的问题是,所有对于索引的添加或者删除操作,mysql数据库是先创建一张新的临时表,然后把数据导入
索引的创建和删除可以通过两种方法;一种是alter table ,另一种是create /drop index.alter table 创建索引的语法:
alter table tbl_name
|add {index|key} {index_name}
{index_type}(index_col_name,......)[index_option].............
|drop{index|key}index_name
alter table tbl_name drop primary key;
create/drop index的语法同样很简单;
create [unique] index index_name
[index_type] on tbl_name(index_col_name...)
drop index index_name on tbl_name;
drop index index_name on tbl_name;
索引可以索引整个列的数据,也可以只索引列的开头部分的数据,如我们前面创建的表t,b列为varchar(8000),我们只索引前100个字段,如;
mysql> alter table t add key idx_b(b(100));
query ok, 0 rows affected (0.05 sec)
records: 0  duplicates: 0  warnings: 0
mysql>
目前mysql数据库存在的一个普遍的问题是,所有对于索引的添加或者删除操作,mysql数据库是先创建一张新的临时表,然后把数据导入临时表,删除原表,再把临时表重名为原来的表名,。因此对于一张大表,添加和删除索引需要很长的时间。
innodb存储引擎从版本innodb plugin开始,支持一种快速索引创建方法;当然这种方法只限制于辅助索引,对于主键的创建和删除还是需要重新创建一个表,对于辅助索引的创建,innodb存储引擎会对表加上一个s锁,。在创建的过程中,不需要重建表 ,因此速度极快。但是在创建过程中,由于上了s锁,,因此创建的过程中该表只能进行读操作,删除辅助索引操作就更简单,只需要在innodb内部视图进行更新,将辅助索引的空间标记为可用,并删除mysql内部视图上对于该表的索引定义即可;
查看表中索引的信息可以使用show index语句,如我们分析表t,之前加一个联合索引,,如:
mysql> alter table t add key idx_a_b(a,c);
query ok, 0 rows affected (0.12 sec)
records: 0  duplicates: 0  warnings: 0
mysql> show index from t\g;
*************************** 1. row ***************************
        table: t
  non_unique: 0
    key_name: primary
 seq_in_index: 1
  column_name: a
    collation: a
  cardinality: 4
    sub_part: null
      packed: null
        null:
  index_type: btree
      comment:
index_comment:
*************************** 2. row ***************************
        table: t
  non_unique: 1
    key_name: idx_c
 seq_in_index: 1
  column_name: c
    collation: a
  cardinality: 4
    sub_part: null
      packed: null
        null:
  index_type: btree
      comment:
index_comment:
*************************** 3. row ***************************
        table: t
  non_unique: 1
    key_name: idx_b
 seq_in_index: 1
  column_name: b
    collation: a
  cardinality: 4
    sub_part: 100
      packed: null
        null: yes
  index_type: btree
      comment:
index_comment:
*************************** 4. row ***************************
        table: t
  non_unique: 1
    key_name: idx_a_b
 seq_in_index: 1
  column_name: a
    collation: a
  cardinality: 4
    sub_part: null
      packed: null
        null:
  index_type: btree
      comment:
index_comment:
*************************** 5. row ***************************
        table: t
  non_unique: 1
    key_name: idx_a_b
 seq_in_index: 2
  column_name: c
    collation: a
  cardinality: 4
    sub_part: null
      packed: null
        null:
  index_type: btree
      comment:
index_comment:
5 rows in set (0.00 sec)
error:
no query specified
mysql>
其它类似信息

推荐信息