The operation of mysql statement on the index

foreword

在日常的开发工作中,对sql进行优化是很有必要的,而优化sql查询的一种方法就是添加索引,来优化慢sql

To create or add an index, you can use the following statements.

1. Use the ALTER TABLE statement to create an index.

The syntax is as follows:

1.PRIMARY KEY(primary key index
mysql>ALTER TABLE 表名 ADD PRIMARY KEY ( 字段 )
2.UNIQUE(unique index)
mysql>ALTER TABLE 表名 ADD UNIQUE (字段 )
3.INDEX(normal index)
mysql>ALTER TABLE 表名 ADD INDEX index_name ( 字段 )
4.FULLTEXT(full text index)
mysql>ALTER TABLE 表名 ADD FULLTEXT ( 字段 )
5. multi-column index
mysql>ALTER TABLE 表名 ADD INDEX index_name ( 字段1, 字段2, 字段3 )

Let's actually test it:
insert image description here
We added a multi-column index to the table sales, the index name is: index_name, the field: (sales_id, customer_id) You
insert image description here
can see that the table currently has 2 indexes, a primary key index, and a multi-column index Index, indicating that our index has been added successfully

Second, use the CREATE INDEX statement to add indexes to the table.

Both common and UNIQUE indexes can be added . Its format is as follows:

// 普通索引
create index 索引名 on table_name (column_list) ;

//唯一索引
create unique index 索引名 on table_name (column_list) ;

Note: 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, PRIMARY KEY indexes cannot be created with the CREATE INDEX statement.

Also let's actually test it:

insert image description here
Let's see the effect:
insert image description here
3. Delete the index.

Dropping an index can be done 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 索引名 on 表名;

alter table 表名 drop index 索引名;

alter table 表名 drop primary key ;

Among them, in the previous two statements,All are based on the index name in the table to delete the index items in the table (including index + index field)

And in the last statement,Only used when deleting PRIMARY KEY indexes, because a table can only have one PRIMARY KEY index, so no need to specify the index name. If no PRIMARY KEY index was created, but the table has one or more UNIQUE indexes, MySQL drops the first UNIQUE index.

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

Guess you like

Origin blog.csdn.net/Ghoul___/article/details/126580940