索引高级

1. XShell环境下进入MySQL
mysql -u root -p
然后输入密码:
指定索引长度
REATE INDEX index_name ON table_name (column_name(length), clolumn_name(length)…);
2. 显示所有的数据库show database ;
mysql> show databases ;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| gg                 |
| hz                 |
| leave_message      |
| mybatis            |
| mysql              |
| performance_schema |
| sys                |
| td                 |
+--------------------+
9 rows in set (0.00 sec)

3. 使用哪个数据库 use gg ;
mysql> use gg
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed

4. 显示所有的表 show tables ;
mysql> show tables
    -> ;
+------------------------+
| Tables_in_gg           |
+------------------------+
| abc                    |
| now_radio              |
| reply                  |
| t1                     |
| t2                     |
| video_accounts         |
| wchat_office_accounts  |
| wechat_friend_accounts |
| weibo_account          |
| words                  |
+------------------------+
10 rows in set (0.00 sec)


5. 创建一个表,不带主键,不带唯一字段,观察是否有索引的产生
mysql> create table test ( id  int (11) not null ,name varchar(50)  ,phone int (11));
Query OK, 0 rows affected (0.01 sec)

5.1结果如下:没有索引产生
mysql> show index from test ;
Empty set (0.00 sec)

5.2 添加主键,观察有无索引产生
mysql> alter table test  add primary key (id) ;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

5.3 再查询索引 ,发现有索引产生
mysql> show index from test ;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| test  |          0 | PRIMARY  |            1 | id          | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
1 row in set (0.01 sec)

6. 添加一个唯一字段,观察有无索引产生
mysql> alter table test add unique (name);
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

6.1 发现产生了一个索引
mysql> show index from test ;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| test  |          0 | PRIMARY  |            1 | id          | A         |           2 |     NULL | NULL   |      | BTREE      |         |               |
| test  |          0 | name     |            1 | name        | A         |           2 |     NULL | NULL   | YES  | BTREE      |         |               |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
2 rows in set (0.00 sec)


6.2 观察查询的时候是否使用了索引,发现确实使用了
mysql> explain select * from test where name ='2';
+----+-------------+-------+------------+-------+---------------+------+---------+-------+------+----------+-------+
| id | select_type | table | partitions | type  | possible_keys | key  | key_len | ref   | rows | filtered | Extra |
+----+-------------+-------+------------+-------+---------------+------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | test  | NULL       | const | name          | name | 53      | const |    1 |   100.00 | NULL  |
+----+-------------+-------+------------+-------+---------------+------+---------+-------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)


explain显示了mysql如何使用索引来处理select语句以及连接表。可以帮助选择更好的索引和写出更优化的查询语句。

下面重点解释一下explain的各个意思:

EXPLAIN列的解释:

table:显示这一行的数据是关于哪张表的

type:这是重要的列,显示连接使用了何种类型。
		从最好到最差的连接类型为const、eq_reg、ref、range、indexhe和ALL

possible_keys:显示可能应用在这张表中的索引。如果为空,没有可能的索引。
						可以为相关的域从WHERE语句中选择一个合适的语句

key: 实际使用的索引。如果为NULL,则没有使用索引。很少的情况下,MYSQL会选择优化不足的索引。
			这种情况下,可以在SELECT语句中使用USE INDEX(indexname)来强制使用一个索引
			或者用IGNORE INDEX(indexname)来强制MYSQL忽略索引

key_len:使用的索引的长度。在不损失精确性的情况下,长度越短越好

ref:显示索引的哪一列被使用了,如果可能的话,是一个常数

rows:MYSQL认为必须检查的用来返回请求数据的行数

Extra:关于MYSQL如何解析查询的额外信息。将在表4.3中讨论,
	但这里可以看到的坏的例子是Using temporary和Using filesort,意思MYSQL根本不能使用索引,结果是检索会很慢

extra列返回的描述的意义

Distinct:一旦MYSQL找到了与行相联合匹配的行,就不再搜索了

Not exists: MYSQL优化了LEFT JOIN,一旦它找到了匹配LEFT JOIN标准的行,就不再搜索了

Range checked for each Record(index map:#):没有找到理想的索引,因此对于从前面表中来的每一个行组合,
			MYSQL检查使用哪个索引,并用它来从表中返回行。这是使用索引的最慢的连接之一

Using filesort: 看到这个的时候,查询就需要优化了。MYSQL需要进行额外的步骤来发现如何对返回的行排序。
			它根据连接类型以及存储排序键值和匹配条件的全部行的行指针来排序全部行

Using index: 列数据是从仅仅使用了索引中的信息而没有读取实际的行动的表返回的,
				这发生在对表的全部的请求列都是同一个索引的部分的时候

Using temporary 看到这个的时候,查询需要优化了。这里,MYSQL需要创建一个临时表来存储结果,
这通常发生在对不同的列集进行ORDER BY上,而不是GROUP BY上

Where used 使用了WHERE从句来限制哪些行将与下一张表匹配或者是返回给用户。如果不想返回表中的全部行,
并且连接类型ALL或index,这就会发生,或者是查询有问题不同连接类型的解释(按照效率高低的顺序排序)

system 表只有一行:system表。这是const连接类型的特殊情况

const:表中的一个记录的最大值能够匹配这个查询(索引可以是主键或惟一索引)。
因为只有一行,这个值实际就是常数,因为MYSQL先读这个值然后把它当做常数来对待

eq_ref:在连接中,MYSQL在查询时,从前面的表中,对每一个记录的联合都从表中读取一个记录,
它在查询使用了索引为主键或惟一键的全部时使用

ref:这个连接类型只有在查询使用了不是惟一或主键的键或者是这些类型的部分(比如,利用最左边前缀)时发生。
对于之前的表的每一个行联合,全部记录都将从表中读出。这个类型严重依赖于根据索引匹配的记录多少—越少越好

range:这个连接类型使用索引返回一个范围中的行,比如使用>或<查找东西时发生的情况

index: 这个连接类型对前面的表中的每一个记录联合进行完全扫描(比ALL更好,因为索引一般小于表数据)

ALL:这个连接类型对于前面的每一个记录联合进行完全扫描,这一般比较糟糕,应该尽量避免
7. 增加普通索引

7.1 增加2列 sex 和 type

mysql> alter table  test add sex char(1);
Query OK, 0 rows affected (0.06 sec)
Records: 0  Duplicates: 0  Warnings: 0


7.2 查看现在的表,同事使sex字段有值,查询id=1 并且sex =0的记录

mysql>  select * from test ;
+----+------+-------+------+------+
| id | name | phone | sex  | type |
+----+------+-------+------+------+
|  1 | 1    |     1 | 0    |    1 |
|  2 | 2    |     2 | 1    |    1 |
+----+------+-------+------+------+
2 rows in set (0.01 sec)


mysql> explain select * from test where sex ='1' and type =1 ;
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | test  | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    2 |    50.00 | Using where |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

7.3 说明在没有建立索引的时候,查询也没有使用到索引,下面为sex添加索引

mysql> alter table test add index sexIndex (sex);
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

7.4查询,说明使用了索引

mysql> explain select * from test where sex ='1' and type =1 ;
+----+-------------+-------+------------+------+---------------+----------+---------+-------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key      | key_len | ref   | rows | filtered | Extra       |
+----+-------------+-------+------------+------+---------------+----------+---------+-------+------+----------+-------------+
|  1 | SIMPLE      | test  | NULL       | ref  | sexIndex      | sexIndex | 2       | const |    1 |    50.00 | Using where |
+----+-------------+-------+------------+------+---------------+----------+---------+-------+------+----------+-------------+
1 row in set, 1 warning (0.01 sec)


7.5 在sex字段有索引的情况下,再建立一个组合索引

mysql> alter table test add index stIndex (sex,type);
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

7.6发现sex 字段存在两个索引,这就是索引的最左原则

mysql> show index from test ;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| test  |          0 | PRIMARY  |            1 | id          | A         |           2 |     NULL | NULL   |      | BTREE      |         |               |
| test  |          0 | name     |            1 | name        | A         |           2 |     NULL | NULL   | YES  | BTREE      |         |               |
| test  |          1 | sexIndex |            1 | sex         | A         |           2 |     NULL | NULL   | YES  | BTREE      |         |               |
| test  |          1 | stIndex  |            1 | sex         | A         |           2 |     NULL | NULL   | YES  | BTREE      |         |               |
| test  |          1 | stIndex  |            2 | type        | A         |           2 |     NULL | NULL   | YES  | BTREE      |         |               |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
5 rows in set (0.01 sec)

7.7 在sex字段有两个索引的情况下,观察到底会使用哪个呢?

mysql> explain select * from test where sex ='1' and type =1 ;
+----+-------------+-------+------------+------+------------------+----------+---------+-------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys    | key      | key_len | ref   | rows | filtered | Extra       |
+----+-------------+-------+------------+------+------------------+----------+---------+-------+------+----------+-------------+
|  1 | SIMPLE      | test  | NULL       | ref  | sexIndex,stIndex | sexIndex | 2       | const |    1 |    50.00 | Using where |
+----+-------------+-------+------------+------+------------------+----------+---------+-------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

7.8 说明它使用了单独的一个


8. 对于组合索引一些长字段的类型比如说varchar类型,长度定义的可能是20 但是建立索引的时候用10就够了

这是因为一般情况下名字的长度不会超过10,这样会加速索引查询速度,还会减少索引文件的大小,提高INSERT的更新速度。

8.1 如果分别在 usernname,city,age上建立单列索引,让该表有3个单列索引,查询时和上述的组合索引效率也会大不一样,远远低于我们的组合索引。虽然此时有了三个索引,但MySQL只能用到其中的那个它认为似乎是最有效率的单列索引。
8.2 建立这样的组合索引,其实是相当于分别建立了下面三组组合索引:

usernname,city,age usernname,city usernname 为什么没有 city,age这样的组合索引呢?这是因为MySQL组合索引“最左前缀”的结果。简单的理解就是只从最左面的开始组合。并不是只要包含这三列的查询都会用到该组合索引.

usernname,city,age  会用到索引
usernname,city  会
username 会

city 不会  
age 不会
city age 不会

但是username age 会不会使用索引呢?

1.
mysql> explain select * from mytable where  username ='admin' and age =10;
+----+-------------+---------+------------+------+---------------+---------------+---------+-------+------+----------+------------------------------------+
| id | select_type | table   | partitions | type | possible_keys | key           | key_len | ref   | rows | filtered | Extra                              |
+----+-------------+---------+------------+------+---------------+---------------+---------+-------+------+----------+------------------------------------+
|  1 | SIMPLE      | mytable | NULL       | ref  | name_city_age | name_city_age | 12      | const |    1 |    20.00 | Using index condition; Using where |
+----+-------------+---------+------------+------+---------------+---------------+---------+-------+------+----------+------------------------------------+
1 row in set, 1 warning (0.00 sec)
2.

mysql> explain select * from mytable where age =10 and  username ='admin';
+----+-------------+---------+------------+------+---------------+---------------+---------+-------+------+----------+------------------------------------+
| id | select_type | table   | partitions | type | possible_keys | key           | key_len | ref   | rows | filtered | Extra                              |
+----+-------------+---------+------------+------+---------------+---------------+---------+-------+------+----------+------------------------------------+
|  1 | SIMPLE      | mytable | NULL       | ref  | name_city_age | name_city_age | 12      | const |    1 |    20.00 | Using index condition; Using where |
+----+-------------+---------+------------+------+---------------+---------------+---------+-------+------+----------+------------------------------------+
1 row in set, 1 warning (0.00 sec)

说明也使用了索引没必要完全满足索引的条件,也就是where条件可能有很多,但是满足索引中的一个就可以使用索引


8.3 那where的顺序会不会使用相同的索引呢?

结果如下: 说明where顺序并不会对索引使用造成影响,但是对性能的影响有没有呢?

1.
mysql> explain select * from mytable  where username ='admin' and age =10 and city ='zz'  ;
+----+-------------+---------+------------+------+---------------+---------------+---------+-------------------+------+----------+-------------+
| id | select_type | table   | partitions | type | possible_keys | key           | key_len | ref               | rows | filtered | Extra       |
+----+-------------+---------+------------+------+---------------+---------------+---------+-------------------+------+----------+-------------+
|  1 | SIMPLE      | mytable | NULL       | ref  | name_city_age | name_city_age | 68      | const,const,const |    1 |   100.00 | Using where |
+----+-------------+---------+------------+------+---------------+---------------+---------+-------------------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

2.
mysql> explain select * from mytable  where age =10  and username ='admin'  and city ='zz'  ;
+----+-------------+---------+------------+------+---------------+---------------+---------+-------------------+------+----------+-------------+
| id | select_type | table   | partitions | type | possible_keys | key           | key_len | ref               | rows | filtered | Extra       |
+----+-------------+---------+------------+------+---------------+---------------+---------+-------------------+------+----------+-------------+
|  1 | SIMPLE      | mytable | NULL       | ref  | name_city_age | name_city_age | 68      | const,const,const |    1 |   100.00 | Using where |
+----+-------------+---------+------------+------+---------------+---------------+---------+-------------------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)


mysql> explain select * from mytable  where  username ='admin'  and city ='zz'   and age =10;
+----+-------------+---------+------------+------+---------------+---------------+---------+-------------------+------+----------+-------------+
| id | select_type | table   | partitions | type | possible_keys | key           | key_len | ref               | rows | filtered | Extra       |
+----+-------------+---------+------------+------+---------------+---------------+---------+-------------------+------+----------+-------------+
|  1 | SIMPLE      | mytable | NULL       | ref  | name_city_age | name_city_age | 68      | const,const,const |    1 |   100.00 | Using where |
+----+-------------+---------+------------+------+---------------+---------------+---------+-------------------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)


A : 建立索引时,应该考虑性能高的排在前面,也就是某个字段查询出来结果少的 排在前面

B: 已经建立好的索引,在使用的时候where的顺序会不会对性能造成影响呢?

MySQL遵循最左前缀原理,当查询条件匹配联合索引的前面几列时,可以使用联合索引;
否则,不会使用联合索引。
如果where字句中的列全都包含在索引列中,那么where字句中的字段顺序和索引顺序无关,
但如果是部分包括的话就要看是否满足最左前缀匹配原则了。

C: where执行顺序是从左往右执行的,

d: 遵守原则:排除越多数据的条件放在第一个。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值