Index correlation

1. Index classification

1. Single-column index: an index contains one column, and a table can contain multiple single-column indexes; it is divided into:
  • normal index
  • primary key index
  • Unique index: similar to the primary key index, the difference: can be NULL, the primary key index cannot

2. Composite index: a composite index contains two or more columns

2. Index creation and deletion

1. Create an index

-- Index type: primary key primary key index, UNIQUE INDEX unique index, INDEX ordinary index, composite index;
-- Index name: see the name, it is not easy to be too long; the unique index unique_index_column_name and the combined index a_b_c_d list the field name union_index in turn; the ordinary index index_(idx_ is abbreviated as)

-- create index
create INDEX index_name on table_name(column_name);
CREATE INDEX account_Index ON `award`(`account`); -- note the notation on the field
alter table table_name add INDEX index_name(column_name);
ALTER TABLE award ADD INDEX account_Index(`account`);


2. Delete the index

DROP INDEX IndexName ON `TableName`;


3. View the index

show INDEX from `TableName`;


3. Storage engine: InnoDB, based on BTree index, the leftmost matching principle, taking the combined index as an example:

1. Create a table


show databases ; -- show databases

use test ; -- use the test database

show tables ; -- show the data tables in the database

 CREATE TABLE `award` (
   `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
   `aty_id` varchar(100) NOT NULL DEFAULT '' COMMENT 'Activity scene id',
   `nickname` varchar(12) NOT NULL DEFAULT '' COMMENT 'User nickname',
   `is_awarded` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Whether the user accepts the award',
   `award_time` int(11) NOT NULL DEFAULT 0 COMMENT 'Award time',
   `account` varchar(12) NOT NULL DEFAULT '' COMMENT '帐号',
   `password` char(32) NOT NULL DEFAULT '' COMMENT 'password',
   `message` varchar(255) NOT NULL DEFAULT '' COMMENT 'Awards information',
   `created_time` int(11) NOT NULL DEFAULT 0 COMMENT 'created time',
   `updated_time` int(11) NOT NULL DEFAULT 0 COMMENT 'Updated time',
   PRIMARY KEY (`id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='Awards Information Table';

desc award ; -- view table structure

show columns from award ; -- view the table structure

alter table award add index nickname_account_create_time(nickname,account,created_time); -- add index, combine index


2. The leftmost matching principle, a_b_c_index(a,b,c) matches the three indexes of a , b , and abc. When combining queries, the query conditions should be roughly the same as the index order.

MySQL has a query optimizer, which will automatically adjust the query conditions according to the index. Execute in order; but it is best to arrange query conditions in the order of the index to facilitate the use of query cache; mysql query cache configuration and viewing
, and keep the same case in SQL queries, do not have both uppercase and lowercase

-- use when querying index
-- matches a
explain select * from award where nickname = "1" ;



-- matches ab
explain select * from award where nickname = "1" and account = "2" ;




-- matches abc
explain select * from award where nickname = "1" and account = "2" and created_time = "2017-10-01";




-- The index is not used when querying

-- The leftmost matching principle, although the account field is included in the composite index, it does not match it
explain select * from award where account = "2" ;




3. Range query like

-- can use
explain select * from award where nickname like "1" ;
-- Can not
explain select * from award where nickname like "%1%" ; -- "%1" 同样
-- Can
explain select * from award where nickname like "1%" ;
-- The leftmost match, the leftmost cannot be ambiguous data




4. The index range query is related to the position. If the leftmost field uses the range query, the subsequent fields in the combined index will be invalid in the index; the latter fields are the same, the second field is queried according to the range, and the third to last field will be invalid. The index of one field is invalid. Querying



according to the range, the index can still be used, but the query efficiency is much lower if the ref is null.


In addition, >= and > are different in use. The former can be used for all index fields, and the latter Only all fields on the left side of the current field can be used. 5. The order by index



alone does not work; it must be used together with the where condition
. .How to judge whether the index is used? type = all Full table retrieval possible_keys Index key that may be used Index key used Index key_len Index length 2. How to determine the number of fields of the index used? key_len key_len length calculation



















  • All index fields, if not set not null, need to add one byte.
  • Fixed-length field, int occupies four bytes, date occupies three bytes, and char(n) occupies n characters.
  • For the field varchar(n), there are n characters + two bytes.
  • Different character sets, the number of bytes occupied by a character is different. For latin1 encoding, one character occupies one byte, for gbk encoding, one character occupies two bytes, and for utf8 encoding, one character occupies three bytes.


-- three index fields
`nickname` varchar(12) NOT NULL DEFAULT '' COMMENT 'User nickname',
`account` varchar(12) NOT NULL DEFAULT '' COMMENT '帐号',     
`created_time` int(11) NOT NULL DEFAULT '0' COMMENT 'created time',     
--According to the above calculation method:
-- used a index: key_len = 12 * 3 + 2 = 38
-- used ab index: key_len = 24 * 3 + 2*2 = 76
-- used abc index: key_len = 24*3 + 2*2 + 4 = 80



Blog reference:
Calculate the index length in MySQL

5. Index advantages
1. The uniqueness of each row of data in the database table can be guaranteed by establishing a unique index or primary key index.
2. Establishing an index can greatly improve the retrieved data and reduce table retrieval. The number of rows
3. The connection conditions in the table join can speed up the direct connection between the table and the table
4. Data retrieval in the grouping and sorting clauses can reduce the time consumed by grouping and sorting in the query time (database records will be reordered)
5. Establishing an index, using an index in a query can improve performance

6. Index disadvantages
1. It will take time to create and maintain an index, and it will increase with the increase of the amount of data
2. The index file will occupy physical space, except that the data table needs In addition to occupying physical space, each index will also occupy a certain amount of physical space
. 3. When INSERT, UPDATE, and DELETE are performed on the data of the table, the index should also be dynamically maintained, which will reduce the speed of data maintenance. Index files that take up disk space. In general, this is not a serious problem, but if you create multiple composite indexes on a large table, the index file will swell quickly).
(After a field is indexed, a physical space will be opened to store the elements in the field according to the BTREE data structure. When data is added, updated, or deleted, the BTree structure needs to be changed again, so later maintenance requires a certain cost)

Seven, matters needing attention
1. On the columns that often need to be searched, the speed of the index can be accelerated
-- the SQL used in the development process will be listed in turn, and then add indexes according to the fields commonly used by the query conditions

2. The primary key column can ensure that column uniqueness
-- The primary key, if it is an int type, you need to specify unsigned unsigned, and the primary key auto_increment will increase automatically

. 3. Adding an index to the join condition between the table and the table can speed up the join query.

4. When ordering is often required (order by ), adding an index to the distinct column of group by and the distinct column can speed up the time of sorting query, (order by alone does not use index, consider adding where or adding limit to index)
-- multi-table association query, when the order of the index is the same as the ORDER When the columns in the BY are in the same order and all the columns are in the same direction (all ascending or all descending), you can use the index to sort. If the query is to join multiple tables, the index will only be used if all columns in the ORDER BY are columns of the first table. In all other cases filesort is used.


5. < <= > >= BETWEEN IN after some where and like in some cases to create an index of the field (B-TREE)
-- >= is different from >. In the combined index, the leftmost field uses > = The entire index can still be used; but > will cause the index of the right field to fail

. 6. Like statement if you create an index on the nickname field. When querying, the statement is nickname lick '%ABC%', then this index speaks It will not work. And nickname lick 'ABC%' will be able to use index

7. The index will not contain NULL columns, if the column contains NULL values, it will not be included in the index, if there is a column in the composite index If it contains NULL value, then this composite index will be invalid, generally need to give the default value of 0 or ' '


8. Use short index, if one of your fields is Char(32) or int(32), specify the prefix length such as the first 10 characters when creating the index (provided that most values ​​are unique..), then short index can be Improve query speed, reduce disk space, and reduce I/0 operations.

9. Do not perform operations on columns, which will invalidate mysql indexes and perform full table scans

. 10. The smaller the data type, the better Good, because usually smaller data types usually occupy less space in disk, memory, cpu, and cache, and are processed faster.

Eight , do not use indexes
1. Columns that are rarely used in queries should not create indexes, if Establishing an index will also reduce the performance of mysql and increase the space requirement.

2. Columns with little data should not be indexed, such as a gender field 0 or 1. In the query, the data of the result set occupies the table The proportion of data rows is relatively large, and mysql needs to scan a large number of rows. Adding indexes will not improve efficiency
--that is, fields with low discrimination do not use indexes

. 3. Columns defined as text, image and bit data types should not be increased. Index, 4. When the table modification (UPDATE, INSERT, DELETE) operation is much larger than the retrieval (SELECT) operation, the index should not be

created. These two operations are

mutually . MySQL - Indexing and Optimization



Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326597294&siteId=291194637