日期:2014-05-16 浏览次数:20422 次
陆陆续续看了一些关于mysql innodb 引擎的文档,但是还是不能回答我自己如何根据查询语言建立索引的问题,所以必须做一些小实验才能解开上述疑惑。
首先,总结下一些文档的内容:
?
?
本文章的主要目的在于:
mysql innodb如何使用索引,即一条sql语句如何使用索引。
?
测试环境
?
建立基础表
?
create table test ( col_pk int primary key,col_index_1 int,col_index_compound_1 int,col_index_coumpount_2 int)engine=innodb,character set=gbk;?
查看主键索引
?
show indexes from test;
?写道
?
我们如下查询:
?
explain select * from test where col_pk = 1; +----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------------------------------+ | 1 | SIMPLE | NULL | NULL | NULL | NULL | NULL | NULL | NULL | Impossible WHERE noticed after reading const tables | +----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------------------------------+?
?
从上面可以看出innoDB选择的常量表进行查询,因为表中没有数据所以查询为不可能执行
然后我们插入数据:
?
insert into test values(1,1,1,1); insert into test values(2,1,1,1); --再次查询 explain select * from test where col_pk = 1; +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+ | 1 | SIMPLE | test | const | PRIMARY | PRIMARY | 4 | const | 1 | | +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+ 1 row in set (0.00 sec)
?
插入数据后我们可以看出,这个查询会使用索引col_pk
?
?
接着我们在test建立索引col_index_1和(col_index_compound_1和col_index_compound_2)的索引
?
create index index_col_index_1 on test(col_index_1); create index index_col_index_compound_12 on test(col_index_compound_1,col_index_coumpount_2); mysql> show indexes from test; +-------+------------+-----------------------------+--------------+-----------------------+-----------+-------------+----------+--------+------+------------+---------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | +-------+------------+-----------------------------+-----------