Home > Database > Mysql Tutorial > Detailed explanation of mysql index usage tips and precautions

Detailed explanation of mysql index usage tips and precautions

黄舟
Release: 2017-03-25 13:39:43
Original
1228 people have browsed it

This article mainly introduces mysqlindex usage skills and notes. The editor thinks it is quite good. Now I will share it with you and give it to everyone. Be a reference. Let’s follow the editor and take a look.

1. The role of index

In general application systems, the read-write ratio is about 10:1 , and insertion operations and general update operations rarely cause performance problems. The most encountered ones, which are also the most likely to cause problems, are some complex query operations, so the optimization of query statements is obviously a top priority. Heavy.

When the amount of data and access is small, mysql access is very fast, and whether or not to add an index has little impact on the access. But when the amount of data and visits increase dramatically, you will find that MySQL slows down or even goes down. In this case, you must consider optimizing SQL. Creating a correct and reasonable index for the database is an important means of MySQL optimization.

The purpose of the index is to improve query efficiency, which can be compared to a dictionary. If we want to look up the word "mysql", we definitely need to locate the m letter, then find the y letter from bottom to bottom, and then find the remaining sql . Without an index, you may need to look through all the words to find what you want. In addition to dictionaries, examples of indexes can be seen everywhere in life, such as train schedules at train stations, catalogs of books, etc. Their principles are the same. By constantly narrowing the scope of the data you want to obtain, you can filter out the final desired results, and at the same time, turn random events into sequential events, that is, we always use the same search method to lock data.

When creating an index, you need to consider which columns will be used in SQL queries, and then create one or more indexes for these columns. In fact, an index is also a table that holds the primary key or index field, and a pointer that points each record to the actual table. Indexes are not visible to database users; they are only used to speed up queries. Database search engines use indexes to quickly locate records.

INSERT and UPDATE statements will take more time to execute on tables with indexes, but SELECT statements will execute faster. This is because when an insert or update is performed, the database also needs to insert or update the index value.

2. Index creation and deletion

Type of index:

  1. UNIQUE (unique Index): The same value cannot appear, there can be NULL value

  2. INDEX (ordinary index): The same index content is allowed to appear

  3. PROMARY KEY (primary key index): The same value is not allowed

  4. fulltext index (full text index): It can target a certain word in the value, but the efficiency is really good Not flattering

  5. Combined index: Essentially, multiple fields are built into one index, and the combination of column values ​​must be unique

(1) Use the ALTER TABLE statement to create simply

and apply it after the table is created and then add it.

ALTER TABLE 表名 ADD 索引类型 (unique,primary key,fulltext,index)[索引名](字段名)
Copy after login
//普通索引
alter table table_name add index index_name (column_list) ;
//唯一索引
alter table table_name add unique (column_list) ;
//主键索引
alter table table_name add primary key (column_list) ;
Copy after login

ALTER TABLE can be used to create three index formats: ordinary index, UNIQUE index and PRIMARY KEY index. table_name is the name of the table to be added to the index. column_list indicates which columns to index. When there are multiple columns, the distance between each column is Separate with commas. The index name index_name is optional. By default, MySQL will assign a name based on the first index column. Additionally, ALTER TABLE allows multiple tables to be altered in a single statement, so multiple indexes can be created simultaneously.

(2) Use the CREATE INDEX statement to add indexes to the table

CREATE INDEX can be used to add ordinary indexes or UNIQUE indexes to the table, and can be used to create indexes when building tables.

CREATE INDEX index_name ON table_name(username(length));
Copy after login

If it is CHAR, VARCHAR type, length can be less than the actual length of the field; if it is BLOB and TEXT type, length must be specified.

//create只能添加这两种索引;
CREATE INDEX index_name ON table_name (column_list)
CREATE UNIQUE INDEX index_name ON table_name (column_list)
Copy after login

table_name, index_name and column_list have the same meaning as in the ALTER TABLE statement, and the index name is not optional. In addition, you cannot use the CREATE INDEX statement to create a PRIMARY KEY index.

(3) Deleting the index

Deleting the index can be achieved using the ALTER TABLE or DROP INDEX statement. DROP INDEX can be processed as a statement inside ALTER TABLE, and its format is as follows:

drop index index_name on table_name ;

alter table table_name drop index index_name ;

alter table table_name drop primary key ;
Copy after login

Among them, in the first two statements, the index index_name in table_name is deleted. In the last statement, it is only used to delete the PRIMARY KEY index, because a table can only have one PRIMARY KEY index, so there is no need to specify the index name. If no PRIMARY KEY index is created, but the table has one or more UNIQUE indexes, MySQL drops the first UNIQUE index.

If a column is deleted from the table, the index will be affected. For a multi-column index, if one of the columns is deleted, the column will also be deleted from the index. If you delete all the columns that make up the index, the entire index will be deleted.

(4) Combined index and prefix index

在这里要指出,组合索引和前缀索引是对建立索引技巧的一种称呼,并不是索引的类型。为了更好的表述清楚,建立一个demo表如下。

create table USER_DEMO
(
  ID          int not null auto_increment comment '主键',
  LOGIN_NAME      varchar(100) not null comment '登录名',
  PASSWORD       varchar(100) not null comment '密码',
  CITY         varchar(30) not null comment '城市',
  AGE         int not null comment '年龄',
  SEX         int not null comment '性别(0:女 1:男)',
  primary key (ID)
);
Copy after login

为了进一步榨取mysql的效率,就可以考虑建立组合索引,即将LOGIN_NAME,CITY,AGE建到一个索引里:

代码如下:

ALTER TABLE USER_DEMO ADD INDEX name_city_age (LOGIN_NAME(16),CITY,AGE);
Copy after login

建表时,LOGIN_NAME长度为100,这里用16,是因为一般情况下名字的长度不会超过16,这样会加快索引查询速度,还会减少索引文件的大小,提高INSERT,UPDATE的更新速度。

如果分别给LOGIN_NAME,CITY,AGE建立单列索引,让该表有3个单列索引,查询时和组合索引的效率是大不一样的,甚至远远低于我们的组合索引。虽然此时有三个索引,但mysql只能用到其中的那个它认为似乎是最有效率的单列索引,另外两个是用不到的,也就是说还是一个全表扫描的过程。

建立这样的组合索引,就相当于分别建立如下三种组合索引:

LOGIN_NAME,CITY,AGE
LOGIN_NAME,CITY
LOGIN_NAME
Copy after login

为什么没有CITY,AGE等这样的组合索引呢?这是因为mysql组合索引“最左前缀”的结果。简单的理解就是只从最左边的开始组合,并不是只要包含这三列的查询都会用到该组合索引。也就是说name_city_age(LOGIN_NAME(16),CITY,AGE)从左到右进行索引,如果没有左前索引,mysql不会执行索引查询。

如果索引列长度过长,这种列索引时将会产生很大的索引文件,不便于操作,可以使用前缀索引方式进行索引,前缀索引应该控制在一个合适的点,控制在0.31黄金值即可(大于这个值就可以创建)。

SELECT COUNT(DISTINCT(LEFT(`title`,10)))/COUNT(*) FROM Arctic; -- 这个值大于0.31就可以创建前缀索引,Distinct去重复

ALTER TABLE `user` ADD INDEX `uname`(title(10)); -- 增加前缀索引SQL,将人名的索引建立在10,这样可以减少索引文件大小,加快索引查询速度
Copy after login

三.索引的使用及注意事项

EXPLAIN可以帮助开发人员分析SQL问题,explain显示了mysql如何使用索引来处理select语句以及连接表,可以帮助选择更好的索引和写出更优化的查询语句。

使用方法,在select语句前加上Explain就可以了:

Explain select * from user where id=1;
Copy after login

尽量避免这些不走索引的sql:

SELECT `sname` FROM `stu` WHERE `age`+10=30;-- 不会使用索引,因为所有索引列参与了计算

SELECT `sname` FROM `stu` WHERE LEFT(`date`,4) <1990; -- 不会使用索引,因为使用了函数运算,原理与上面相同

SELECT * FROM `houdunwang` WHERE `uname` LIKE&#39;后盾%&#39; -- 走索引

SELECT * FROM `houdunwang` WHERE `uname` LIKE "%后盾%" -- 不走索引

-- 正则表达式不使用索引,这应该很好理解,所以为什么在SQL中很难看到regexp关键字的原因

-- 字符串与数字比较不使用索引;
CREATE TABLE `a` (`a` char(10));
EXPLAIN SELECT * FROM `a` WHERE `a`="1" -- 走索引
EXPLAIN SELECT * FROM `a` WHERE `a`=1 -- 不走索引

select * from dept where dname=&#39;xxx&#39; or loc=&#39;xx&#39; or deptno=45 
--如果条件中有or,即使其中有条件带索引也不会使用。换言之,就是要求使用的所有字段,都必须建立索引, 我们建议大家尽量避免使用or 关键字
Copy after login

-- 如果mysql估计使用全表扫描要比使用索引快,则不使用索引

索引虽然好处很多,但过多的使用索引可能带来相反的问题,索引也是有缺点的:

  1. 虽然索引大大提高了查询速度,同时却会降低更新表的速度,如对表进行INSERT,UPDATE和DELETE。因为更新表时,mysql不仅要保存数据,还要保存一下索引文件

  2. 建立索引会占用磁盘空间的索引文件。一般情况这个问题不太严重,但如果你在要给大表上建了多种组合索引,索引文件会膨胀很宽

索引只是提高效率的一个方式,如果mysql有大数据量的表,就要花时间研究建立最优的索引,或优化查询语句。

使用索引时,有一些技巧:

1.索引不会包含有NULL的列

只要列中包含有NULL值,都将不会被包含在索引中,复合索引中只要有一列含有NULL值,那么这一列对于此符合索引就是无效的。

 2.使用短索引

对串列进行索引,如果可以就应该指定一个前缀长度。例如,如果有一个char(255)的列,如果在前10个或20个字符内,多数值是唯一的,那么就不要对整个列进行索引。短索引不仅可以提高查询速度而且可以节省磁盘空间和I/O操作。

3.索引列排序

mysql查询只使用一个索引,因此如果where子句中已经使用了索引的话,那么order by中的列是不会使用索引的。因此数据库默认排序可以符合要求的情况下不要使用排序操作,尽量不要包含多个列的排序,如果需要最好给这些列建复合索引。

4.like语句操作

一般情况下不鼓励使用like操作,如果非使用不可,注意正确的使用方式。like ‘%aaa%'不会使用索引,而like ‘aaa%'可以使用索引。

5.不要在列上进行运算

6.不使用NOT IN 、<>、!=操作,但<,<=,=,>,>=,BETWEEN,IN是可以用到索引的

7.索引要建立在经常进行select操作的字段上。

这是因为,如果这些列很少用到,那么有无索引并不能明显改变查询速度。相反,由于增加了索引,反而降低了系统的维护速度和增大了空间需求。

8.索引要建立在值比较唯一的字段上。

9.对于那些定义为text、image和bit数据类型的列不应该增加索引。因为这些列的数据量要么相当大,要么取值很少。

10.在where和join中出现的列需要建立索引。

11. If there is an inequality sign (where column != ...) in the query condition of where, mysql will not be able to use the index.

12. If a function is used in the query condition of the where clause (such as: where DAY(column)=...), mysql will not be able to use the index.

13. In the join operation (when data needs to be extracted from multiple data tables), mysql can only use the index when the data type of the primary key and the foreign key is the same, otherwise the index will not be used if it is established in time.

The above is the detailed content of Detailed explanation of mysql index usage tips and precautions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template