Mysql table index (summary)

Table of contents

foreword

✨✨✨Hello everyone, I am Flying Fish-blog. Today I will introduce Mysql to you. If there are any shortcomings, please give me your advice. Thank you for your support! ! !

1. An overview of the index

1. Index type

2. Index storage

3. Index advantages and disadvantages

4. Suggestions for use

5. Create and view indexes

2. Ordinary index

1. Define the index when creating the table

 2. Create an index on an existing table

(1). Point to the create statement

(2). Point to the alter table statement

3. View index execution

3. Unique index

1. Create a table definition index

2. Create an index on an existing table

(1). Create command to create

(2). alter command to create 

4. Full text index

1. Define the index when creating the table

2. Create an index on an existing table

(1). Execute the create statement

(2). Execute the alter table statement

3. Usage scenarios

4. MySQL8 Chinese word segmentation support

Five, multi-column index

1. Define the index when creating the table

2. Create an index on an existing table

(1). Execute the create statement

(2). Execute the alter table statement

6. Hide, delete and modify indexes

1. Hidden index

2. Delete the index

7. Index Design Principles

1. Choose a unique index

2. Suggest indexes for fields that often require sorting, grouping, and union operations

3. Build indexes for fields that are often used as query conditions

4. Limit the number of indexes

5. Try to use indexes with less data

6. Try to use prefixes to index

7. Delete indexes that are no longer used or rarely used

Summarize


✨✨✨Hello everyone, I am Flying Fish-blog. Today I will introduce Mysql to you. If there are any shortcomings, please give me your advice. Thank you for your support! ! !

 

foreword

        In daily life, we often look up the phone number of "someone" in the phone book, search by surname or sort by alphabet; look up the pronunciation and meaning of "a certain word" in the dictionary, etc., to quickly find specific records. Here, both "surname" and "letter" can be regarded as indexes, and querying by "surname" or "letter" is querying by index!

        An index is a special database structure that can be used to quickly query specific records in a database table, and is an important way to improve database performance. In MySQL, all data types can be indexed.

        Through the index, you don't have to read all the information of the record when querying the data, but just query the index column, otherwise the database system will read all the information of each record for matching. For example, the index is equivalent to the phonetic table of the Xinhua dictionary. If you want to look up the word "Guo", if the phonetic sequence is not applicable, you need to turn hundreds of pages from the first page of the dictionary; if you extract the pinyin to form the phonetic table, You only need to search directly from the sequence table of more than 10 pages, which can greatly save time. Therefore, the use of indexes can greatly improve the query speed of the database and effectively improve the performance of the database system.


1. An overview of the index

1. Index type

        Indexes include ordinary indexes, unique indexes, full-text indexes, single-column indexes, multi-column indexes, and spatial indexes. Will be introduced in detail below~

2. Index storage

        There are two main storage types for database underlying index implementation, B-tree (BTREE) and hash (HASH) index, InnoDB and MyISAM use BTREE index; MEMORY storage engine can use BTREE and HASH index, and BTREE is used by default. In this case, the engine used by the database is InnoDB.

3. Index advantages and disadvantages

        advantage:

                Can improve the speed of retrieving data.

        shortcoming:

                Creating and maintaining indexes takes time, and the time-consuming amount increases with the increase of data volume; indexes need to occupy physical space, and each index occupies a certain amount of physical space; when adding, deleting and modifying data, indexes must be dynamically maintained , resulting in a reduction in data maintenance speed.

4. Suggestions for use

        Indexes can improve the speed of query, but it will affect the speed of inserting records, because when inserting records into an indexed table, the database system will sort according to the index, which reduces the speed of inserting records, and the speed of inserting a large number of records is affected more obvious. In this case, the best way is to delete the index in the table first, then insert the data, and then create the index after the insertion is complete.

5. Create and view indexes

        Creating an index refers to building an index on one or more columns of a table in order to improve the access speed of the table. There are three ways to create an index, namely creating an index when creating a table, creating an index on an existing table, and using the ALTER TABLE statement to create an index. This section will explain these three creation methods in detail according to the specific index classification.

2. Ordinary index

1. Define the index when creating the table

CREATE TABLE tablename(

    propname1 type1,

    propname2 type2,

    ……

    propnamen type..n,

     INDEX | KEY

    [indexname] (propnamen [(length)] [ ASC | DESC ] ) );

         Among them, the parameters INDEX and KEY are used to specify the field as an index, and you can choose one of them, and the effect is the same; the parameter indexname is the name of the index, which can be omitted; the parameter propnamen is the name of the field corresponding to the index, the The field must be a defined field; the parameter length is an optional parameter, which refers to the length of the index, and must be a string type to be used; the parameters ASC and DESC are both optional parameters, ASC means ascending order, DESC means descending order , or ascending order if not specified.

 2. Create an index on an existing table

(1). Point to the create statement

CREATE INDEX indexname 

    ON tablename (propname [(length)] [ASC|DESC]); 

         The parameter INDEX is used to specify the field as an index, which cannot be KEY here; the parameter indexname is the name of the newly created index; the parameter tablename refers to the name of the table that needs to create an index, the table must already exist, if it does not exist, It needs to be created first; the parameter propname specifies the name of the field corresponding to the index, and the field must be a previously defined field; the parameter length is an optional parameter, indicating the length of the index, and must be a string type to be used; the parameters ASC and DESC are both It is an optional parameter, ASC means ascending order, DESC means descending order, and the default is ascending order.

mysql> create database school;   #创建数据库school 

mysql> use school;   #选择数据库school 

mysql> create table class(id int, name varchar(128) UNIQUE, teacher varchar(64));       #创建表class, 并建立为id 字段索引 

mysql> create index index_id on class(id ASC);  #追加升序索引 

mysql> show create table class;  #查看表定义 

mysql> insert into class values(1, '一班', 'Martin');  # 插入记录1

mysql> insert into class values(1, '二班', 'Rock');   # 插入记录2

mysql> select * from class where id > 0 ;   #根据id查询记录,结果将降序排列 

(2). Point to the alter table statement

ALTER TABLE tablename ADD INDEX | KEY indexname 

     (propname [(length)] [ASC|DESC]); 

          In the above statement, the parameter tablename is the table that needs to be indexed; the keyword IDNEX or KEY is used to specify the creation of a common index; the parameter indexname is used to specify the name of the created index; the parameter propname is used to specify the name of the field associated with the index; The parameter length is used to specify the length of the index; the parameter ASC is used to specify ascending sort; the parameter DESC is used to specify descending sort.

3. View index execution

        EXPLAIN query statement

        Output result:

key : The actual index to use. If NULL, no index is used

possible_keys : Displays the indexes that may be applied to this table, one or more. If there is an index on the fields involved in the query, the index will be listed, but not necessarily actually used by the query

key_len : Indicates the number of bytes used in the index, through which the length of the index used in the query can be calculated. The shorter the value, the better!

3. Unique index

1. Create a table definition index

        The so-called unique index means that when creating an index, the field values ​​of the restricted index must be unique. This type of index can query a certain record faster than ordinary indexes.

CREATE TABLE tablename(

    propname1 type1,

    ……

    propnamen type..n,

    UNIQUE INDEX | KEY [indexname] (propnamen [(length)] [ ASC | DESC ] ) );

        Note: The parameters UNIQUE INDEX and UNIQUE KEY are used to specify the field as an index, and you can choose one of them; the parameter indexname is the name of the index, which can be omitted; the parameter propnamen is the name of the field corresponding to the index, which must be the previous The defined field must be defined as a UNIQUE constraint; the parameter length is an optional parameter, which refers to the length of the index, and must be a string type to be used; the parameters ASC and DESC are optional parameters, ASC means ascending order, and DESC means Sort in descending order, or ascending if not specified.

2. Create an index on an existing table

(1). Create command to create

CREATE UNIQUE INDEX indexname 

    ON tablename (propname [(length)] [ASC|DESC]); 

(2). alter command to create 

ALTER TABLE tablename ADD UNIQUE INDEX | KEY indexname (propname [(length)] [ASC|DESC]); 

4. Full text index

        The full-text index mainly builds a word-segment-based index for the string type, mainly based on the fields of CHAR, VARCHAR, and TEXT, so that the string-type fields with a large amount of data can be queried more quickly.

        The full-text index is based on words, and MySQL's default word segmentation is that all special symbols other than letters and numbers are word separators.

        MySQL has supported full-text indexes since version 3.23.23. Previously, MySQL 5.6 could only create full-text indexes on data tables whose storage engine was MyISAM. After 5.6, InnoDB began to support full-text indexes (and after 5.7, it supports Chinese full-text indexes). By default, the search execution mode of the full-text index is case-insensitive. If the field associated with the full-text index is a binary data type, the search execution mode is case-sensitive.

1. Define the index when creating the table

The following code:

CREATE TABLE tablename(

    propname1 type1,

    propname2 type2,

    ……

    propnamen type..n,

    FULLTEXT INDEX | KEY

    [indexname] (propnamen [(length)] ) );

Actual code:

mysql> create database school;   #创建数据库school 

mysql> use school;   #选择数据库school 

mysql>create table class(id int, name varchar(128) UNIQUE, teacher varchar(64),comment varchar(1024),FULLTEXT INDEX index_comm(comment));       #创建表class, 并建立为comment 字段为全文索引 

mysql> insert into class values(1,'1班','Martin','我是一个兵,来自老百姓!');  # 插入记录1

mysql> insert into class values(2,'2班','Rock','此班主任毕业自唐僧系');   # 插入记录2

mysql> insert into class values(3,'3班','Janny','I''m Miss Zhang.');   #插入记录3 

mysql> select * from class where match(comment) AGAINST('我是一个兵');#利用全文检索索引快速查询记录

2. Create an index on an existing table

(1). Execute the create statement

        In addition to the SQL statement FULLTEXT INDEX to create a full-text index in MySQL, it can also be implemented through the SQL statement CREATE FULLTEXT INDEX, and its syntax is as follows:

CREATE FULLTEXT INDEX indexname

    ON tablename( propname1 [ ( length ) ] );

        In the above statement, the keyword CREATE FULLTEXT INDEX is used to create a full-text index.

        The following example table already exists, you can create a full-text index through the CREATE statement:

mysql> create database school;   #创建数据库school 

mysql> use school;   #选择数据库school 

mysql> create table class(id int, name varchar(128) UNIQUE, teacher varchar(64));       #创建表class, 并建立为id 字段索引 

mysql> create FULLTEXT index index_teacher on class(teacher );  #追加全文索引 

mysql> show create table class;  #查看表定义 

(2). Execute the alter table statement

         In addition to the above two ways to create a full-text index, creating a full-text index in MySQL can also be achieved through the SQL statement ALTER, and its syntax is as follows:

ALTER TABLE tablename

    ADD FULLTEXT INDEX|KEY indexname(propname [(length)]);

3. Usage scenarios

Full-text search data based on full-text index fields:

SELECT * FROM table name WHERE MATCH(`column name`) AGAINST('keyword');

mysql> create database school;   #创建数据库school 

mysql> use school;   #选择数据库school 

mysql> mysql> create table class(id int, name varchar(128) UNIQUE, teacher varchar(64),info varchar(1024),FULLTEXT INDEX index_des(info));       #创建表class, 并建立为info 字段为全文索引 

mysql> insert into class values(1,'1班','Martin','我是一个兵,来自老百姓!');  # 插入记录1

mysql> insert into class values(2,'2班','Rock','此班主任毕业自唐僧系');   # 插入记录2

mysql> insert into class values(3,'3班','Janny','I'm Miss Zhang.');   # 插入记录3

mysql> select * from class where match(teacher) AGAINST('我是一个兵');#根据id查询记录

4. MySQL8 Chinese word segmentation support

         Add the following configuration items to the configuration file my.ini (Windows 10 default path: C:\ProgramData\MySQL\MySQL Server 8.0), and restart the MySQL80 service at the same time:

[mysqld]
ngram_token_size=2
mysql> create database school;   #创建数据库school 

mysql> use school;   #选择数据库school 

mysql> mysql> create table class(id int, name varchar(128) UNIQUE, teacher varchar(64),comment varchar(1024),FULLTEXT INDEX index_des(comment) with parser   ngram);       #创建表class, 并建立为comment 字段为全文索引 

mysql> insert into class values(1,'1班','Martin','我是一个兵,来自老百姓!');  # 插入记录1

mysql> insert into class values(2,'2班','Rock','此班主任毕业自唐僧系');   # 插入记录2

mysql> insert into class values(3,'3班','Janny','I''m Miss Zhang.');   #插入记录3

mysql> select * from class where match(comment) AGAINST('百姓');#利用全文检索索引快速查询记录

mysql> select * from class where match(comment) AGAINST('唐僧');#利用全文检索索引快速查询记录

Five, multi-column index

        A multi-column index means that when creating an index, the associated field is not one field, but multiple fields. Although the associated fields can be queried, only the first field in the associated fields is used in the query condition , the multi-column index will be used.

1. Define the index when creating the table

CREATE TABLE tablename(

    propname1 type1,

    ……

    propnamen type..n,

    INDEX | KEY [indexname] (propname1 [(length)] [ ASC | DESC ],

                             Propname2 [(length)] [ ASC | DESC ],

                              ... ...                              

                             Propnamen [(length)] [ ASC | DESC ])

);

Note: It is basically the same as the ordinary index definition, the difference is that multiple index columns are added.

mysql> create database school;   #创建数据库school 

mysql> use school;   #选择数据库school 

mysql> create table class(id int, name varchar(128) UNIQUE, teacher varchar(64), INDEX index_mult_columns(id, teacher));       #创建表class, 并建立包含id,teacher字段的多列索引 

mysql> show create table class;  #查看表定义 

mysql> insert into class values(1, '一班', 'Martin');  # 插入记录1

mysql> insert into class values(1, '二班', 'Rock');   # 插入记录2

mysql> select * from class where id > 0 ;   #仅根据id查询记录会启用多列索引 

2. Create an index on an existing table

(1). Execute the create statement

CREATE INDEX indexname

    ON tablename( propname1 [(length)] [ ASC | DESC ], 

                   Propname2 [(length)] [ ASC | DESC ],  

                              ... ...                                

                         Propnamen [(length)] [ ASC | DESC ]  );

        In the above statement, the keyword CREATE INDEX is used to create a multi-column index.

        The following example table already exists, and a multi-column index can be created through the CREATE statement:

mysql> create database school;   #创建数据库school 

mysql> use school;   #选择数据库school 

mysql> create table class(id int, name varchar(128) UNIQUE, teacher varchar(64));       #创建表class, 并建立为id 字段索引 

mysql> create  index index_id on class(id, name );  #追加多列索引 

mysql> show create table class;  #查看表定义 

(2). Execute the alter table statement

        In addition to the above two ways to create a full-text index, creating a full-text index in MySQL can also be achieved through the SQL statement ALTER, and its syntax is as follows:

ALTER TABLE tablename

    ADD INDEX|KEY indexname(propname1 [(length)] [ ASC | DESC ], 

                   Propname2 [(length)] [ ASC | DESC ],             

                              ... ...                                          

                         Propnamen [(length)] [ ASC | DESC ]  );

6. Hide, delete and modify indexes

1. Hidden index

        MySQL 8 began to support hidden indexes. Hidden indexes provide more user-friendly database operations. 

        Hidden index, as the name suggests, makes the index temporarily invisible and will not be used by the optimizer. Indexes are visible by default. Hidden indexes can be used to test the performance of indexes. There is no need to delete the index when verifying the necessity of the index, you can hide the index first, and you can actually delete the index if the performance of the optimizer has no impact.

ALTER TABLE tablename ALTER  INDEX  index_name INVISIBLE;  #隐藏索引

ALTER TABLE tablename ALTER  INDEX  index_name VISIBLE;    #取消隐藏

2. Delete the index

        The so-called delete index is to delete the index that has been created in the table. The reason to delete the index is because these indexes will reduce the update speed of the table and affect the performance of the database.

        Deleting an index in MySQL is implemented through the SQL statement DROP INDEX, and its syntax is as follows:

DROP INDEX indexname ON tablename; 

7. Index Design Principles

1. Choose a unique index

         The value of the unique index is unique, and a record can be determined more quickly through the index. For example, the student number in the student table is a unique field. Building a unique index for this field can quickly determine the information of a student. If the name is used, the phenomenon of the same name may exist, thereby reducing the query speed

2. Suggest indexes for fields that often require sorting, grouping, and union operations

        Fields that often require operations such as ORDER BY, GROUP BY, DISTINCT, and UNION will waste a lot of time in sorting operations. If they are indexed, sorting operations can be effectively avoided.

3. Build indexes for fields that are often used as query conditions

        If a field is often used as a query condition, the query speed of this field will affect the query speed of the entire table, and indexing such a field can improve the query speed of the entire table.

4. Limit the number of indexes

         The number of indexes is not as many as possible. Each index needs to occupy disk space. The more indexes, the more disk space is required. When modifying the table, it is very troublesome to reconstruct and update the index.

5. Try to use indexes with less data

        If the indexed value is very long, then the speed of the query will be affected. For example, a full-text search of a field of type CHAR(100) will definitely take more time than a field of type CHAR(10).

6. Try to use prefixes to index

        If the indexed value is long, it is better to use a prefix of the value to index. For example, for fields of type TEXT and BLOG, it would be a waste of time to perform a full-text search. If only a few characters in front of the field are searched, the search speed can be improved.

7. Delete indexes that are no longer used or rarely used

        After a large amount of data in the table is updated, or the way the data is used is changed, some original indexes may no longer be needed. DBAs should regularly identify these indexes and delete them to reduce the impact of indexes on update operations.


Summarize

✨✨✨The above is the summary of my study. I hope everyone will discuss, discuss, and work together to move towards a better tomorrow! ! !

Guess you like

Origin blog.csdn.net/m0_65635427/article/details/130308032