(六)MySQL索引

一、索引介绍

1.索引的介绍

索引是对数据库表中一列或者多列的值进行排序的一种结构,使用索引可提高数据库中特定数据的查询速度。

索引是一个单独的、存储在磁盘上的数据库结构,它们包含着对数据表里所有记录的引用指针。

使用索引用于快速找出在某个或多个列中有一特定值得行,所有MySQL列类型都可以被索引,对相关列使用索引是提高查询操作速度的最佳途径。

索引是在存储引擎中实现的,因此,每种存储引擎的索引都不一定完全相同,并且每种存储引擎也不一定支持索引类型。根据存储引擎定义每个表的最大索引数和最大索引长度。所有存储引擎支持每个表至少16个索引,总索引长度至少为256字节。

MyISAM ,InnoDB支持btree索引 Memory 支持 btree和hash索引。

2.索引的优势

  • 加快查询速度
  • 创建唯一索引来保证数据表中数据的唯一性
  • 实现数据的完整性,加速表和表之间的连接
  • 减少分组和排序的时间

3.索引的劣势

增加索引也有许多不利,主要表现在如下几个方面:

  • 创建索引和维护索引要耗费时间,并且随着数据量的增加所耗费的时间也会增加。
  • 索引需要占磁盘空间,除了数据表占数据空间之外,每一个索引还要占一定的物理空间,如果有大量的索引,索引文件可能比数据文件更快达到最大文件尺寸。
  • 当对表中的数据进行增加、删除和修改的时候,索引也要动态地维护,这样就降低了数据的维护速度。

4.索引的分类

(1)唯一索引和普通索引

普通索引是MySQL中的基本索引类型,允许在定义索引的列中插入重复值和空值。

唯一索引,索引列的值必须唯一,但允许有空值。如果是组合索引,则列值的组合必须唯一。

主键索引是一种特殊的唯一索引,不允许有空值。

(2)单列索引和组合索引

单列索引即一个索引只包含单个列,一个表可以有多个单列索引。

组合索引指在表的多个字段组合上创建的索引。只有在查询条件中使用了这些字段的左边字段时,索引才会被使用。使用组合索引时遵循最左前缀集合。

(3)全文索引 fulltext

全文索引类型为FULLTEXT,在定义索引的列上支持值得全文查找,允许在这些索引列中插入重复值和空值。全文索引可以在CHAR、VARCHAR或者TEXT类型的列上创建。MySQL中只有MyISAM存储引擎支持全文索引。

(4)空间索引

空间索引是对空间数据类型的字段建立的索引,MySQL中的空间数据类型有4中,分别是:geometry、point、linstring和polygon 。

MySQL使用SPATIAL关键字进行扩展,使得能够用于创建空间索引的列,必须将其声明为NOT NULL,空间索引只能在存储引擎为MyISAM的表中创建。

5.创建索引的规则

(1)创建索引并非是越多越好,一个表中如果有大量的索引,不仅占用磁盘空间,而且会影响insert、delete、update等语句的性能。因为当表中的数据更改时,索引也会进行调整和更新。

(2)数据量小得表最好不要创建索引,由于数据较少,查询花费的时间可能比遍历索引的时间还要长。

(3)避免对经常更新的数据创建索引。而对经常用于查询的字段应该创建索引。

(4)在条件表达式中经常用到的不同值较多的列创建索引

(5)当唯一性是某种数据本身的特征时,我们创建唯一性索引

(6)在频繁进行排序或分组的列上建立索引,如果排序的列有多个,可以创建组合索引

二、创建表的同时创建索引

Create index 创建索引 alter table 添加索引 Create table 表名[字段名 数据类型] [unique唯一索引|fulltext全文索引|spatial空间索引] [index|key] [索引名] (col_name [length]) [asc |desc]

语法帮助:

mysql> help index
Many help items for your request exist.
To make a more specific request, please type 'help <item>',
where <item> is one of the following
topics:ALTER TABLECACHE INDEXCREATE INDEXCREATE TABLEDROP INDEXJOINLOAD INDEXSHOWSHOW INDEXSPATIAL INDEXESmysql> help create index
Name: 'CREATE INDEX'
Description:
Syntax:
CREATE [UNIQUE | FULLTEXT | SPATIAL] INDEX index_name[index_type]ON tbl_name (key_part,...)[index_option][algorithm_option | lock_option] ...key_part:col_name [(length)] [ASC | DESC]index_option: {KEY_BLOCK_SIZE [=] value| index_type| WITH PARSER parser_name| COMMENT 'string'
}index_type:USING {BTREE | HASH}algorithm_option:ALGORITHM [=] {DEFAULT | INPLACE | COPY}lock_option:LOCK [=] {DEFAULT | NONE | SHARED | EXCLUSIVE}Normally, you create all indexes on a table at the time the table
itself is created with CREATE TABLE. See [HELP CREATE TABLE]. This
guideline is especially important for InnoDB tables, where the primary
key determines the physical layout of rows in the data file. CREATE
INDEX enables you to add indexes to existing tables.CREATE INDEX is mapped to an ALTER TABLE statement to create indexes.
See [HELP ALTER TABLE]. CREATE INDEX cannot be used to create a PRIMARY
KEY; use ALTER TABLE instead. For more information about indexes, see
https://dev.mysql.com/doc/refman/5.7/en/mysql-indexes.html.URL: https://dev.mysql.com/doc/refman/5.7/en/create-index.htmlmysql>

1.普通索引 index

创建普通索引:普通索引是最基础的索引类型,没有唯一性的限制。作用是只加快对数据的访问速度。

mysql> create table book(-> bookid int not null,-> bookname varchar(255) not null,-> authors varchar(255) not null,-> info varchar(255) null,-> comment varchar(255) null,-> year_publication year not null,-> index(year_publication));
Query OK, 0 rows affected (0.56 sec)mysql> desc book;
+------------------+--------------+------+-----+---------+-------+
| Field            | Type         | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+-------+
| bookid           | int(11)      | NO   |     | NULL    |       |
| bookname         | varchar(255) | NO   |     | NULL    |       |
| authors          | varchar(255) | NO   |     | NULL    |       |
| info             | varchar(255) | YES  |     | NULL    |       |
| comment          | varchar(255) | YES  |     | NULL    |       |
| year_publication | year(4)      | NO   | MUL | NULL    |       |
+------------------+--------------+------+-----+---------+-------+
6 rows in set (0.00 sec)mysql>

查看创建的索引

mysql> show create table book\G
*************************** 1. row ***************************Table: book
Create Table: CREATE TABLE `book` (`bookid` int(11) NOT NULL,`bookname` varchar(255) NOT NULL,`authors` varchar(255) NOT NULL,`info` varchar(255) DEFAULT NULL,`comment` varchar(255) DEFAULT NULL,`year_publication` year(4) NOT NULL,KEY `year_publication` (`year_publication`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312
1 row in set (0.00 sec)mysql>

用explain 判断索引是否正在被使用

mysql> explain select * from book where year_publication=1999\G
*************************** 1. row ***************************id: 1select_type: SIMPLEtable: bookpartitions: NULLtype: ref
possible_keys: year_publicationkey: year_publicationkey_len: 1ref: constrows: 1filtered: 100.00Extra: Using index condition
1 row in set, 1 warning (0.00 sec)mysql> explain select * from book where bookname="xxxx"\G
*************************** 1. row ***************************id: 1select_type: SIMPLEtable: bookpartitions: NULLtype: ALL
possible_keys: NULLkey: NULLkey_len: NULLref: NULLrows: 1filtered: 100.00Extra: Using where
1 row in set, 1 warning (0.00 sec)mysql>

TYPE的取值范围有:System const ref eq_ref index all range

system>const>eq_ref>ref>range>index>ALL
越往左边,性能越高,比如system就比ALL类型性能要高出许多,其中system、const只是理想类型,基本达不到;

我们自己实际能优化到ref>range这两个类型,就是你自己写SQL,如果你没优化基本上就是ALL,如果你优化了,那就尽量达到ref>range这两个级别;

左边基本达不到!

所以,要对type优化的前提是,你需要有索引,如果你连索引都没有创建,那你就不用优化了,肯定是ALL…;

2.唯一索引 unique index

创建唯一索引:唯一索引主要原因是减少查询索引列操作的执行时间。尤其是对比比较庞大的数据表。与普通索引类似,不同点在于:索引列的值必须唯一,但允许有空值。如果是组合索引,则列值的组合必须唯一。

案例一:

Database changed
mysql> create table t1(-> id int not null,                    #不能为空-> name char(30) not null,-> unique index UnidIdx(id));      #唯一索引
Query OK, 0 rows affected (0.64 sec)mysql>

查看创建的索引

mysql> show create table t1\G
*************************** 1. row ***************************Table: t1
Create Table: CREATE TABLE `t1` (`id` int(11) NOT NULL,`name` char(30) NOT NULL,UNIQUE KEY `UnidIdx` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312
1 row in set (0.00 sec)mysql> desc t1;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(11)  | NO   | PRI | NULL    |       |         #PRI自动创建的
| name  | char(30) | NO   |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)mysql> insert into t1 values(1,"zhao");
Query OK, 1 row affected (0.00 sec)mysql> insert into t1(name) values("qian");
ERROR 1364 (HY000): Field 'id' doesn't have a default value
#报错原因:id不能为空,必须填写mysql> insert into t1 values(1,"qian");
ERROR 1062 (23000): Duplicate entry '1' for key 'UnidIdx'
#报错原因:id为主键,不能重复
mysql>

案例二:

mysql> create table tt1( -> id int ,                           #可以为空-> name char(30) not null, -> unique index UnidIdx(id));     #唯一索引
Query OK, 0 rows affected (0.53 sec)mysql>

查看创建的索引

mysql> show create table tt1\G
*************************** 1. row ***************************Table: tt1
Create Table: CREATE TABLE `tt1` (`id` int(11) DEFAULT NULL,`name` char(30) NOT NULL,UNIQUE KEY `UnidIdx` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312
1 row in set (0.00 sec)mysql> desc tt1;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(11)  | YES  | UNI | NULL    |       |             #唯一的
| name  | char(30) | NO   |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)mysql> insert into tt1 values(1,"zhao");
Query OK, 1 row affected (0.00 sec)mysql> insert into tt1(name) values("qian");                    #此时id可以为空
Query OK, 1 row affected (0.00 sec)mysql> insert into tt1 values(1,"qian");
ERROR 1062 (23000): Duplicate entry '1' for key 'UnidIdx'
#报错原因:id为UnidIdx,是唯一的不能重复mysql>

3.单列索引

单列索引:是在数据表中的某一字段上创建的索引,一个表中可以创建多个单列索引。

mysql> create table t2(-> id int not null,-> name char(30) null,-> index singleIdx(name));
Query OK, 0 rows affected (0.02 sec)mysql>

查看创建的索引

mysql> desc t2;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(11)  | NO   |     | NULL    |       |
| name  | char(30) | YES  | MUL | NULL    |       |             #MUL单列索引
+-------+----------+------+-----+---------+-------+
2 rows in set (0.02 sec)mysql> show create table t2\G
*************************** 1. row ***************************Table: t2
Create Table: CREATE TABLE `t2` (`id` int(11) NOT NULL,`name` char(30) DEFAULT NULL,KEY `singleIdx` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312
1 row in set (0.00 sec)mysql> insert into t2 values(1,"zhao");
Query OK, 1 row affected (0.00 sec)mysql> insert into t2 values(1,"zhao");
Query OK, 1 row affected (0.00 sec)mysql> insert into t2(id) values(2);
Query OK, 1 row affected (0.00 sec)mysql> select * from t2;
+----+------+
| id | name |
+----+------+
|  1 | zhao |
|  1 | zhao |               #可重复,没有什么约束
|  2 | NULL |
+----+------+
3 rows in set (0.00 sec)mysql>

4.组合索引

组合索引:是在多个字段上创建一个索引。

**遵循最左前缀原则。**最左前缀:索引最左边的列来匹配行

mysql> create table t3(-> id int not null,-> name char(30) not null,-> age int not null,-> info varchar(255),-> index MultiIdx(id,name,age));
Query OK, 0 rows affected (0.13 sec)mysql>

查看创建的索引

mysql> desc t3;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | int(11)      | NO   | MUL | NULL    |       |     #MUL,因为创建时id在最前面
| name  | char(30)     | NO   |     | NULL    |       |
| age   | int(11)      | NO   |     | NULL    |       |
| info  | varchar(255) | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
4 rows in set (0.04 sec)mysql> show create table t3\G
*************************** 1. row ***************************Table: t3
Create Table: CREATE TABLE `t3` (`id` int(11) NOT NULL,`name` char(30) NOT NULL,`age` int(11) NOT NULL,`info` varchar(255) DEFAULT NULL,KEY `MultiIdx` (`id`,`name`,`age`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312
1 row in set (0.00 sec)mysql> insert into t3 values(1,"zhao",38,"xxxx");
Query OK, 1 row affected (0.00 sec)mysql> insert into t3 values(1,"qian",38,"xxxx");
Query OK, 1 row affected (0.00 sec)mysql> insert into t3 values(1,"qian",38,"xxxx");
Query OK, 1 row affected (0.00 sec)mysql> select * from t3;
+----+------+-----+------+
| id | name | age | info |
+----+------+-----+------+
|  1 | zhao |  38 | xxxx |
|  1 | qian |  38 | xxxx |
|  1 | qian |  38 | xxxx |
+----+------+-----+------+
3 rows in set (0.00 sec)mysql>

组合索引可以起几个索引的作用,但是使用时并不是随意查询哪个字段都是可以使用索引。而是遵循最左前缀:利用索引中最左边的列集来匹配行。这样的列集称为最左前缀。

mysql> explain select * from t3 where id=123\G           #查询id显示使用了索引
*************************** 1. row ***************************id: 1select_type: SIMPLEtable: t3partitions: NULLtype: ref
possible_keys: MultiIdxkey: MultiIdxkey_len: 4ref: constrows: 1filtered: 100.00Extra: NULL
1 row in set, 1 warning (0.00 sec)mysql> explain select * from t3 where name="zhao"\G         #查询name不显示使用了索引
*************************** 1. row ***************************id: 1select_type: SIMPLEtable: t3partitions: NULLtype: ALL
possible_keys: NULLkey: NULLkey_len: NULLref: NULLrows: 3filtered: 33.33Extra: Using where
1 row in set, 1 warning (0.00 sec)mysql> explain select * from t3 where age=18\G            #查询age不显示使用了索引
*************************** 1. row ***************************id: 1select_type: SIMPLEtable: t3partitions: NULLtype: ALL
possible_keys: NULLkey: NULLkey_len: NULLref: NULLrows: 3filtered: 33.33Extra: Using where
1 row in set, 1 warning (0.01 sec)mysql> explain select * from t3 where id=123 and name="zhao"\G
*************************** 1. row ***************************id: 1select_type: SIMPLEtable: t3partitions: NULLtype: ref
possible_keys: MultiIdxkey: MultiIdxkey_len: 64ref: const,constrows: 1filtered: 100.00Extra: NULL
1 row in set, 1 warning (0.04 sec)mysql> explain select * from t3 where id=123 and name="zhao" and age=18\G
*************************** 1. row ***************************id: 1select_type: SIMPLEtable: t3partitions: NULLtype: ref
possible_keys: MultiIdxkey: MultiIdxkey_len: 68ref: const,const,constrows: 1filtered: 100.00Extra: NULL
1 row in set, 1 warning (0.52 sec)mysql> explain select * from t3 where name="zhao" and age=18\G
*************************** 1. row ***************************id: 1select_type: SIMPLEtable: t3partitions: NULLtype: ALL
possible_keys: NULLkey: NULLkey_len: NULLref: NULLrows: 3filtered: 33.33Extra: Using where
1 row in set, 1 warning (0.00 sec)mysql>

5.全文索引 fulltext index

全文索引:FULLTEXT,可以用于全文搜索,只有MyISAM存储引擎支持,并且只为CHAR\VARCHAR和TEXT 列。索引总是对整个列进行,不支持局部索引,适合大型数据的表创建

案例一:

mysql> create table t4(-> id int not null,-> name char(30) not null,-> age int not null,-> info varchar(255),-> fulltext index fullIdx(info(100)));
Query OK, 0 rows affected (0.30 sec)mysql>

查看创建的索引

mysql> desc t4;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | int(11)      | NO   |     | NULL    |       |
| name  | char(30)     | NO   |     | NULL    |       |
| age   | int(11)      | NO   |     | NULL    |       |
| info  | varchar(255) | YES  | MUL | NULL    |       |
+-------+--------------+------+-----+---------+-------+
4 rows in set (0.00 sec)mysql> show create table t4\G
*************************** 1. row ***************************Table: t4
Create Table: CREATE TABLE `t4` (`id` int(11) NOT NULL,`name` char(30) NOT NULL,`age` int(11) NOT NULL,`info` varchar(255) DEFAULT NULL,FULLTEXT KEY `fullIdx` (`info`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312
1 row in set (0.00 sec)mysql> insert into t4 values (1,"test1",18,"One is always on a strange road, watching strange scenery and listening to strange music. Then one day, you will find that the things you try hard to forget are already gone.");
Query OK, 1 row affected (0.01 sec)mysql> insert into t4 values (2,"test2",19,"Love is a lamp, while friendship is the shadow. When the lamp is off,you will find the shadow everywhere. Friend is who can give you strength at last.");
Query OK, 1 row affected (0.00 sec)mysql> insert into t4 values (3,"test3",20,"Happiness is not about being immortal nor having food or rights in one's hand. It’s about having each tiny wish come true, or having something to eat when you are hungry or having someone's love when you need love.");
Query OK, 1 row affected (0.61 sec)mysql> insert into t4 values (4,"test4",21,"Don’t forget the things you once you owned. Treasure the things you can’t get. Don't give up the things that belong to you and keep those lost things in memory.");
Query OK, 1 row affected (0.02 sec)mysql> insert into t4 values (5,"test5",22,"No matter how cruel the destiny treats one with tribulation and misfortune, it will correspondingly treat him with happiness and sweetness. Even if the happiness is short and false, it's enough to light up the whole future life.");
Query OK, 1 row affected (0.00 sec)mysql> select * from t4;              #查看全表
+----+-------+-----+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| id | name  | age | info                                                                                                                                                                                                                                 |
+----+-------+-----+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|  1 | test1 |  18 | One is always on a strange road, watching strange scenery and listening to strange music. Then one day, you will find that the things you try hard to forget are already gone.                                                       |
|  2 | test2 |  19 | Love is a lamp, while friendship is the shadow. When the lamp is off,you will find the shadow everywhere. Friend is who can give you strength at last.                                                                               |
|  3 | test3 |  20 | Happiness is not about being immortal nor having food or rights in one's hand. It’s about having each tiny wish come true, or having something to eat when you are hungry or having someone's love when you need love.               |
|  4 | test4 |  21 | Don’t forget the things you once you owned. Treasure the things you can’t get. Don't give up the things that belong to you and keep those lost things in memory.                                                                     |
|  5 | test5 |  22 | No matter how cruel the destiny treats one with tribulation and misfortune, it will correspondingly treat him with happiness and sweetness. Even if the happiness is short and false, it's enough to light up the whole future life. |
+----+-------+-----+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
5 rows in set (0.00 sec)mysql>
mysql> select * from t4 where match(info) against("one");              #检索one这个单词
+----+-------+-----+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| id | name  | age | info                                                                                                                                                                                                                                 |
+----+-------+-----+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|  1 | test1 |  18 | One is always on a strange road, watching strange scenery and listening to strange music. Then one day, you will find that the things you try hard to forget are already gone.                                                       |
|  3 | test3 |  20 | Happiness is not about being immortal nor having food or rights in one's hand. It’s about having each tiny wish come true, or having something to eat when you are hungry or having someone's love when you need love.               |
|  5 | test5 |  22 | No matter how cruel the destiny treats one with tribulation and misfortune, it will correspondingly treat him with happiness and sweetness. Even if the happiness is short and false, it's enough to light up the whole future life. |
+----+-------+-----+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
3 rows in set (0.07 sec)mysql>
mysql> select * from t4 where match(info) against("everywhere");       #检索everywhere这个单词
+----+-------+-----+--------------------------------------------------------------------------------------------------------------------------------------------------------+
| id | name  | age | info                                                                                                                                                   |
+----+-------+-----+--------------------------------------------------------------------------------------------------------------------------------------------------------+
|  2 | test2 |  19 | Love is a lamp, while friendship is the shadow. When the lamp is off,you will find the shadow everywhere. Friend is who can give you strength at last. |
+----+-------+-----+--------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)mysql>
mysql> insert into t4 values (6,"test6",23,"冷暖百态,韶华知味,时光深处,有多少喜怒哀乐,演绎在游离的梦寐。青涩动荡的年代,没来得及惜别,也没来得及成熟,就悄然溜走。荣辱得失,聚散离合,如云卷云舒,没有谁能抓在手里肆意掌控。");
Query OK, 1 row affected (0.02 sec)mysql> select * from t4 where match(info) against("韶华");        #但是这种查找是不能看中文的,要想查看必须使用分词器
Empty set (0.00 sec)mysql>

查看MySQL自带的分词器

mysql> help against
Name: 'MATCH AGAINST'
Description:
Syntax:
MATCH (col1,col2,...) AGAINST (expr [search_modifier])MySQL has support for full-text indexing and searching:o A full-text index in MySQL is an index of type FULLTEXT.o Full-text indexes can be used only with InnoDB or MyISAM tables, andcan be created only for CHAR, VARCHAR, or TEXT columns.o MySQL provides a built-in full-text ngram parser that supportsChinese, Japanese, and Korean (CJK), and an installable MeCabfull-text parser plugin for Japanese. Parsing differences areoutlined inhttps://dev.mysql.com/doc/refman/5.7/en/fulltext-search-ngram.html,andhttps://dev.mysql.com/doc/refman/5.7/en/fulltext-search-mecab.html.
#MySQL提供了内置的全文ngram解析器,支持中文、日文、韩文(CJK),可安装MeCab全文解析器插件,用于日语。o A FULLTEXT index definition can be given in the CREATE TABLEstatement when a table is created, or added later using ALTER TABLEor CREATE INDEX.o For large data sets, it is much faster to load your data into a tablethat has no FULLTEXT index and then create the index after that, thanto load data into a table that has an existing FULLTEXT index.Full-text searching is performed using MATCH() ... AGAINST syntax.
MATCH() takes a comma-separated list that names the columns to be
searched. AGAINST takes a string to search for, and an optional
modifier that indicates what type of search to perform. The search
string must be a string value that is constant during query evaluation.
This rules out, for example, a table column because that can differ for
each row.There are three types of full-text searches:o A natural language search interprets the search string as a phrase innatural human language (a phrase in free text). There are no specialoperators, with the exception of double quote (") characters. Thestopword list applies. For more information about stopword lists, seehttps://dev.mysql.com/doc/refman/5.7/en/fulltext-stopwords.html.Full-text searches are natural language searches if the IN NATURALLANGUAGE MODE modifier is given or if no modifier is given. For moreinformation, seehttps://dev.mysql.com/doc/refman/5.7/en/fulltext-natural-language.html.o A boolean search interprets the search string using the rules of aspecial query language. The string contains the words to search for.It can also contain operators that specify requirements such that aword must be present or absent in matching rows, or that it should beweighted higher or lower than usual. Certain common words (stopwords)are omitted from the search index and do not match if present in thesearch string. The IN BOOLEAN MODE modifier specifies a booleansearch. For more information, seehttps://dev.mysql.com/doc/refman/5.7/en/fulltext-boolean.html.o A query expansion search is a modification of a natural languagesearch. The search string is used to perform a natural languagesearch. Then words from the most relevant rows returned by the searchare added to the search string and the search is done again. Thequery returns the rows from the second search. The IN NATURALLANGUAGE MODE WITH QUERY EXPANSION or WITH QUERY EXPANSION modifierspecifies a query expansion search. For more information, seehttps://dev.mysql.com/doc/refman/5.7/en/fulltext-query-expansion.html.URL: https://dev.mysql.com/doc/refman/5.7/en/fulltext-search.htmlExamples:
mysql> SELECT id, body, MATCH (title,body) AGAINST('Security implications of running MySQL as root'IN NATURAL LANGUAGE MODE) AS scoreFROM articles WHERE MATCH (title,body) AGAINST('Security implications of running MySQL as root'IN NATURAL LANGUAGE MODE);
+----+-------------------------------------+-----------------+
| id | body                                | score           |
+----+-------------------------------------+-----------------+
|  4 | 1. Never run mysqld as root. 2. ... | 1.5219271183014 |
|  6 | When configured properly, MySQL ... | 1.3114095926285 |
+----+-------------------------------------+-----------------+
2 rows in set (0.00 sec)mysql>

案例二:

mysql> create table tt4(-> id int not null,-> title varchar(255),-> content text,-> fulltext index fulltext_title_content(title,content) with parser ngram);
Query OK, 0 rows affected (0.71 sec)mysql>

查看创建的索引

mysql> desc tt4;
+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| id      | int(11)      | NO   |     | NULL    |       |
| title   | varchar(255) | YES  | MUL | NULL    |       |
| content | text         | YES  |     | NULL    |       |
+---------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)mysql> insert into tt4 values(1,'test1','人活一世,世事多艰,很多事情无能为力,很多委屈生生咽下。最愚笨的,是陷入一种困境,忘记天地很宽 ,路的尽头还能转弯。其实,这人生啊,就是一次体验爱与恨,聚与散,悲与欢的过程。');
Query OK, 1 row affected (0.02 sec)mysql> insert into tt4 values(2,'test2','或许,每一个卑微的灵魂深处,都藏着一份无可言说的苦涩。别人觉得你无坚不摧,却不知你笑容的背后.苦熬了多少个春秋。');
Query OK, 1 row affected (0.00 sec)mysql> insert into tt4 values(3,'test3','读懂了生命之重,也看淡了得失之轻,人生最重要的,莫过于内心的自足。一颗自足的心,可跳出世俗的贪 念,一边大大咧咧苟且着,一边怀着深情诗意着。不羡慕谁,不埋怨谁,在阳光下灿烂,在风雨中也从容。');
Query OK, 1 row affected (0.02 sec)mysql> select * from tt4;                     #查看全表
+----+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| id | title | content                                                                                                                                                                                                                                                                                    |
+----+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|  1 | test1 | 人活一世,世事多艰,很多事情无能为力,很多委屈生生咽下。最愚笨的,是陷入一种困境,忘记天地很宽,路的尽头还能转弯。其实,这人生啊,就是一次体验爱与恨,聚与散,悲与欢的过程。                                                                                                               |
|  2 | test2 | 或许,每一个卑微的灵魂深处,都藏着一份无可言说的苦涩。别人觉得你无坚不摧,却不知你笑容的背后,苦熬了多少个春秋。                                                                                                                                                                           |
|  3 | test3 | 读懂了生命之重,也看淡了得失之轻,人生最重要的,莫过于内心的自足。一颗自足的心,可跳出世俗的贪念,一边大大咧咧苟且着,一边怀着深情诗意着。不羡慕谁,不埋怨谁,在阳光下灿烂,在风雨中也从容。                                                                                               |
+----+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
3 rows in set (0.00 sec)mysql> select * from tt4 where match(title,content) against("灵魂");     #可搜索文字
+----+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| id | title | content                                                                                                                                                                  |
+----+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|  2 | test2 | 或许,每一个卑微的灵魂深处,都藏着一份无可言说的苦涩。别人觉得你无坚不摧,却不知你笑容的背后,苦熬了多少个春秋。                                                         |
+----+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)mysql>

6.空间索引 spatial index

空间索引:必须在MyISAM类型的表中创建,且空间类型的字段必须为非空。 创建

mysql> create table t5(-> g geometry not null,-> spatial index spaIdx(g));
Query OK, 0 rows affected (0.57 sec)mysql>

查看创建的索引

mysql> desc t5;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| g     | geometry | NO   | MUL | NULL    |       |
+-------+----------+------+-----+---------+-------+
1 row in set (0.00 sec)mysql> show create table t5\G
*************************** 1. row ***************************Table: t5
Create Table: CREATE TABLE `t5` (`g` geometry NOT NULL,SPATIAL KEY `spaIdx` (`g`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312
1 row in set (0.00 sec)mysql>

三、在已存在的表上创建索引(修改表Alter table)

1.基本语法

Alter table 表名 add [unique唯一索引|fulltext全文索引|spatial空间索引] [index|key] [默认索引名] (定义索引名[length]) [asc|desc]

2.添加普通索引

mysql> desc book;
+------------------+--------------+------+-----+---------+-------+
| Field            | Type         | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+-------+
| bookid           | int(11)      | NO   |     | NULL    |       |
| bookname         | varchar(255) | NO   |     | NULL    |       |
| authors          | varchar(255) | NO   |     | NULL    |       |
| info             | varchar(255) | YES  |     | NULL    |       |
| comment          | varchar(255) | YES  |     | NULL    |       |
| year_publication | year(4)      | NO   | MUL | NULL    |       |
+------------------+--------------+------+-----+---------+-------+
6 rows in set (0.00 sec)mysql> alter table book add index BKNameIdx(bookname(30));
Query OK, 0 rows affected (0.65 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql>

查看索引

mysql> desc book;
+------------------+--------------+------+-----+---------+-------+
| Field            | Type         | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+-------+
| bookid           | int(11)      | NO   |     | NULL    |       |
| bookname         | varchar(255) | NO   | MUL | NULL    |       |
| authors          | varchar(255) | NO   |     | NULL    |       |
| info             | varchar(255) | YES  |     | NULL    |       |
| comment          | varchar(255) | YES  |     | NULL    |       |
| year_publication | year(4)      | NO   | MUL | NULL    |       |
+------------------+--------------+------+-----+---------+-------+
6 rows in set (0.00 sec)mysql> show create table book\G
*************************** 1. row ***************************Table: book
Create Table: CREATE TABLE `book` (`bookid` int(11) NOT NULL,`bookname` varchar(255) NOT NULL,`authors` varchar(255) NOT NULL,`info` varchar(255) DEFAULT NULL,`comment` varchar(255) DEFAULT NULL,`year_publication` year(4) NOT NULL,KEY `year_publication` (`year_publication`),KEY `BKNameIdx` (`bookname`(30))
) ENGINE=InnoDB DEFAULT CHARSET=gb2312
1 row in set (0.00 sec)mysql> show index from book\G
*************************** 1. row ***************************Table: bookNon_unique: 1Key_name: year_publicationSeq_in_index: 1Column_name: year_publicationCollation: ACardinality: 0Sub_part: NULLPacked: NULLNull: Index_type: BTREEComment:
Index_comment:
*************************** 2. row ***************************Table: bookNon_unique: 1Key_name: BKNameIdxSeq_in_index: 1Column_name: booknameCollation: ACardinality: 0Sub_part: 30Packed: NULLNull: Index_type: BTREEComment:
Index_comment:
2 rows in set (0.00 sec)mysql>

3.添加唯一索引

mysql> alter table book add unique index uniqIdx(bookid);
Query OK, 0 rows affected (0.55 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql>

查看索引

mysql> desc book;
+------------------+--------------+------+-----+---------+-------+
| Field            | Type         | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+-------+
| bookid           | int(11)      | NO   | PRI | NULL    |       |
| bookname         | varchar(255) | NO   | MUL | NULL    |       |
| authors          | varchar(255) | NO   |     | NULL    |       |
| info             | varchar(255) | YES  |     | NULL    |       |
| comment          | varchar(255) | YES  |     | NULL    |       |
| year_publication | year(4)      | NO   | MUL | NULL    |       |
+------------------+--------------+------+-----+---------+-------+
6 rows in set (0.00 sec)mysql> show index from book\G
*************************** 1. row ***************************Table: bookNon_unique: 0Key_name: uniqIdxSeq_in_index: 1Column_name: bookidCollation: ACardinality: 0Sub_part: NULLPacked: NULLNull: Index_type: BTREEComment:
Index_comment:
*************************** 2. row ***************************Table: bookNon_unique: 1Key_name: year_publicationSeq_in_index: 1Column_name: year_publicationCollation: ACardinality: 0Sub_part: NULLPacked: NULLNull: Index_type: BTREEComment:
Index_comment:
*************************** 3. row ***************************Table: bookNon_unique: 1Key_name: BKNameIdxSeq_in_index: 1Column_name: booknameCollation: ACardinality: 0Sub_part: 30Packed: NULLNull: Index_type: BTREEComment:
Index_comment:
3 rows in set (0.00 sec)mysql>

4.添加单列索引

mysql> alter table book add index BKIdex(comment(50));
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql>

查看索引

mysql> desc book;
+------------------+--------------+------+-----+---------+-------+
| Field            | Type         | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+-------+
| bookid           | int(11)      | NO   | PRI | NULL    |       |
| bookname         | varchar(255) | NO   | MUL | NULL    |       |
| authors          | varchar(255) | NO   |     | NULL    |       |
| info             | varchar(255) | YES  |     | NULL    |       |
| comment          | varchar(255) | YES  | MUL | NULL    |       |
| year_publication | year(4)      | NO   | MUL | NULL    |       |
+------------------+--------------+------+-----+---------+-------+
6 rows in set (0.00 sec)mysql> show index from book\G
*************************** 1. row ***************************Table: bookNon_unique: 0Key_name: uniqIdxSeq_in_index: 1Column_name: bookidCollation: ACardinality: 0Sub_part: NULLPacked: NULLNull: Index_type: BTREEComment:
Index_comment:
*************************** 2. row ***************************Table: bookNon_unique: 1Key_name: year_publicationSeq_in_index: 1Column_name: year_publicationCollation: ACardinality: 0Sub_part: NULLPacked: NULLNull: Index_type: BTREEComment:
Index_comment:
*************************** 3. row ***************************Table: bookNon_unique: 1Key_name: BKNameIdxSeq_in_index: 1Column_name: booknameCollation: ACardinality: 0Sub_part: 30Packed: NULLNull: Index_type: BTREEComment:
Index_comment:
*************************** 4. row ***************************Table: bookNon_unique: 1Key_name: BKIdexSeq_in_index: 1Column_name: commentCollation: ACardinality: 0Sub_part: 50Packed: NULLNull: YESIndex_type: BTREEComment:
Index_comment:
4 rows in set (0.00 sec)mysql>

5.添加全文索引

mysql> create table t6(-> id int not null,-> info char(255));
Query OK, 0 rows affected (0.01 sec)mysql> alter table t6 add fulltext index InfoFullIdx(info);
Query OK, 0 rows affected, 1 warning (0.27 sec)
Records: 0  Duplicates: 0  Warnings: 1mysql>

查看索引

mysql> desc t6;
+-------+-----------+------+-----+---------+-------+
| Field | Type      | Null | Key | Default | Extra |
+-------+-----------+------+-----+---------+-------+
| id    | int(11)   | NO   |     | NULL    |       |
| info  | char(255) | YES  | MUL | NULL    |       |
+-------+-----------+------+-----+---------+-------+
2 rows in set (0.00 sec)mysql> show index from t6\G
*************************** 1. row ***************************Table: t6Non_unique: 1Key_name: InfoFullIdxSeq_in_index: 1Column_name: infoCollation: NULLCardinality: 0Sub_part: NULLPacked: NULLNull: YESIndex_type: FULLTEXTComment:
Index_comment:
1 row in set (0.00 sec)mysql>

6.添加组合索引

mysql> alter table book add index BKAUthAndInfoIdx(authors(20),info(50));
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql>

查看索引

mysql> show index from book\G
*************************** 1. row ***************************Table: bookNon_unique: 0Key_name: uniqIdxSeq_in_index: 1Column_name: bookidCollation: ACardinality: 0Sub_part: NULLPacked: NULLNull: Index_type: BTREEComment:
Index_comment:
*************************** 2. row ***************************Table: bookNon_unique: 1Key_name: year_publicationSeq_in_index: 1Column_name: year_publicationCollation: ACardinality: 0Sub_part: NULLPacked: NULLNull: Index_type: BTREEComment:
Index_comment:
*************************** 3. row ***************************Table: bookNon_unique: 1Key_name: BKNameIdxSeq_in_index: 1Column_name: booknameCollation: ACardinality: 0Sub_part: 30Packed: NULLNull: Index_type: BTREEComment:
Index_comment:
*************************** 4. row ***************************Table: bookNon_unique: 1Key_name: BKIdexSeq_in_index: 1Column_name: commentCollation: ACardinality: 0Sub_part: 50Packed: NULLNull: YESIndex_type: BTREEComment:
Index_comment:
*************************** 5. row ***************************Table: bookNon_unique: 1Key_name: BKAUthAndInfoIdxSeq_in_index: 1Column_name: authorsCollation: ACardinality: 0Sub_part: 20Packed: NULLNull: Index_type: BTREEComment:
Index_comment:
*************************** 6. row ***************************Table: bookNon_unique: 1Key_name: BKAUthAndInfoIdxSeq_in_index: 2Column_name: infoCollation: ACardinality: 0Sub_part: 50Packed: NULLNull: YESIndex_type: BTREEComment:
Index_comment:
6 rows in set (0.00 sec)mysql>

7.添加空间索引

mysql> create table t7(-> g geometry not null);
Query OK, 0 rows affected (0.51 sec)mysql> alter table t7 add spatial index spatIdx(g);
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql>

查看索引

mysql> desc t7;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| g     | geometry | NO   | MUL | NULL    |       |
+-------+----------+------+-----+---------+-------+
1 row in set (0.00 sec)mysql> show index from t7\G
*************************** 1. row ***************************Table: t7Non_unique: 1Key_name: spatIdxSeq_in_index: 1Column_name: gCollation: ACardinality: 0Sub_part: 32Packed: NULLNull: Index_type: SPATIALComment:
Index_comment:
1 row in set (0.00 sec)mysql>

四、在已存在的表上创建索引(创建表Create index)

1.语法

Create index 已存在的表上创建索引 Create [unique唯一性索引|fulltext全文索引|spatial空间索引] index 索引名 On 表名(col_name[lenth]..)[asc|desc]

用create table创建的索引可以不添加索引名(不添加索引名默认为字段名) 但是用create index 添加索引名必须加索引名

创建一个book1的表

mysql> create table book1(-> bookid int not null,-> bookname varchar(255) not null,-> authors varchar(255) not null,-> info varchar(255) null,-> comment varchar(255) null,-> year_publication year not null);
Query OK, 0 rows affected (0.02 sec)mysql> desc book1;
+------------------+--------------+------+-----+---------+-------+
| Field            | Type         | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+-------+
| bookid           | int(11)      | NO   |     | NULL    |       |
| bookname         | varchar(255) | NO   |     | NULL    |       |
| authors          | varchar(255) | NO   |     | NULL    |       |
| info             | varchar(255) | YES  |     | NULL    |       |
| comment          | varchar(255) | YES  |     | NULL    |       |
| year_publication | year(4)      | NO   |     | NULL    |       |
+------------------+--------------+------+-----+---------+-------+
6 rows in set (0.04 sec)mysql>

2.普通索引

mysql> create index bknameidex on book1(bookname);
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql> desc book1;
+------------------+--------------+------+-----+---------+-------+
| Field            | Type         | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+-------+
| bookid           | int(11)      | NO   |     | NULL    |       |
| bookname         | varchar(255) | NO   | MUL | NULL    |       |
| authors          | varchar(255) | NO   |     | NULL    |       |
| info             | varchar(255) | YES  |     | NULL    |       |
| comment          | varchar(255) | YES  |     | NULL    |       |
| year_publication | year(4)      | NO   |     | NULL    |       |
+------------------+--------------+------+-----+---------+-------+
6 rows in set (0.00 sec)mysql> show index from book1\G
*************************** 1. row ***************************Table: book1Non_unique: 1Key_name: bknameidexSeq_in_index: 1Column_name: booknameCollation: ACardinality: 0Sub_part: NULLPacked: NULLNull: Index_type: BTREEComment:
Index_comment:
1 row in set (0.00 sec)mysql>

3.单列索引

mysql> create index bkcmtIdex on book1(comment);
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql> show index from book1\G
*************************** 1. row ***************************Table: book1Non_unique: 1Key_name: bknameidexSeq_in_index: 1Column_name: booknameCollation: ACardinality: 0Sub_part: NULLPacked: NULLNull: Index_type: BTREEComment:
Index_comment:
*************************** 2. row ***************************Table: book1Non_unique: 1Key_name: bkcmtIdexSeq_in_index: 1Column_name: commentCollation: ACardinality: 0Sub_part: NULLPacked: NULLNull: YESIndex_type: BTREEComment:
Index_comment:
2 rows in set (0.00 sec)mysql>

4.组合索引

mysql> create index BKAuthAndInfoIdex on book1(authors(30),info(50));
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql> show index from book1\G
*************************** 1. row ***************************Table: book1Non_unique: 1Key_name: bknameidexSeq_in_index: 1Column_name: booknameCollation: ACardinality: 0Sub_part: NULLPacked: NULLNull: Index_type: BTREEComment:
Index_comment:
*************************** 2. row ***************************Table: book1Non_unique: 1Key_name: bkcmtIdexSeq_in_index: 1Column_name: commentCollation: ACardinality: 0Sub_part: NULLPacked: NULLNull: YESIndex_type: BTREEComment:
Index_comment:
*************************** 3. row ***************************Table: book1Non_unique: 1Key_name: BKAuthAndInfoIdexSeq_in_index: 1Column_name: authorsCollation: ACardinality: 0Sub_part: 30Packed: NULLNull: Index_type: BTREEComment:
Index_comment:
*************************** 4. row ***************************Table: book1Non_unique: 1Key_name: BKAuthAndInfoIdexSeq_in_index: 2Column_name: infoCollation: ACardinality: 0Sub_part: 50Packed: NULLNull: YESIndex_type: BTREEComment:
Index_comment:
4 rows in set (0.00 sec)mysql>

5.全文索引

mysql> create table tt6(-> id int not null,-> info char(255));
Query OK, 0 rows affected (0.02 sec)mysql> create fulltext index fullIdex on tt6(info);
Query OK, 0 rows affected, 1 warning (0.24 sec)
Records: 0  Duplicates: 0  Warnings: 1mysql> show index from tt6\G
*************************** 1. row ***************************Table: tt6Non_unique: 1Key_name: fullIdexSeq_in_index: 1Column_name: infoCollation: NULLCardinality: 0Sub_part: NULLPacked: NULLNull: YESIndex_type: FULLTEXTComment:
Index_comment:
1 row in set (0.00 sec)mysql>

6.唯一索引

mysql> create unique index UniqIdx on book1(bookid);
Query OK, 0 rows affected (0.04 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql> show index from book1\G
*************************** 1. row ***************************Table: book1Non_unique: 0Key_name: UniqIdxSeq_in_index: 1Column_name: bookidCollation: ACardinality: 0Sub_part: NULLPacked: NULLNull: Index_type: BTREEComment:
Index_comment:
*************************** 2. row ***************************Table: book1Non_unique: 1Key_name: bknameidexSeq_in_index: 1Column_name: booknameCollation: ACardinality: 0Sub_part: NULLPacked: NULLNull: Index_type: BTREEComment:
Index_comment:
*************************** 3. row ***************************Table: book1Non_unique: 1Key_name: bkcmtIdexSeq_in_index: 1Column_name: commentCollation: ACardinality: 0Sub_part: NULLPacked: NULLNull: YESIndex_type: BTREEComment:
Index_comment:
*************************** 4. row ***************************Table: book1Non_unique: 1Key_name: BKAuthAndInfoIdexSeq_in_index: 1Column_name: authorsCollation: ACardinality: 0Sub_part: 30Packed: NULLNull: Index_type: BTREEComment:
Index_comment:
*************************** 5. row ***************************Table: book1Non_unique: 1Key_name: BKAuthAndInfoIdexSeq_in_index: 2Column_name: infoCollation: ACardinality: 0Sub_part: 50Packed: NULLNull: YESIndex_type: BTREEComment:
Index_comment:
5 rows in set (0.00 sec)mysql>

7.空间索引

mysql> create table tt7 (g geometry not null);
Query OK, 0 rows affected (0.03 sec)mysql> create spatial index SpaIdx on tt7(g);
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql> show index from tt7\G
*************************** 1. row ***************************Table: tt7Non_unique: 1Key_name: SpaIdxSeq_in_index: 1Column_name: gCollation: ACardinality: 0Sub_part: 32Packed: NULLNull: Index_type: SPATIALComment:
Index_comment:
1 row in set (0.00 sec)mysql>

五、删除索引

Alter table 表名 drop index 索引名;

查看book中有多少索引,准备开始删除

mysql> show create table book1\G
*************************** 1. row ***************************Table: book1
Create Table: CREATE TABLE `book1` (`bookid` int(11) NOT NULL,`bookname` varchar(255) NOT NULL,`authors` varchar(255) NOT NULL,`info` varchar(255) DEFAULT NULL,`comment` varchar(255) DEFAULT NULL,`year_publication` year(4) NOT NULL,UNIQUE KEY `UniqIdx` (`bookid`),KEY `bknameidex` (`bookname`),KEY `bkcmtIdex` (`comment`),KEY `BKAuthAndInfoIdex` (`authors`(30),`info`(50))
) ENGINE=InnoDB DEFAULT CHARSET=gb2312
1 row in set (0.00 sec)mysql>

1.用ALTER TABLE 删除

mysql> alter table book1 drop index bknameidex;
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql> show create table book1\G
*************************** 1. row ***************************Table: book1
Create Table: CREATE TABLE `book1` (`bookid` int(11) NOT NULL,`bookname` varchar(255) NOT NULL,`authors` varchar(255) NOT NULL,`info` varchar(255) DEFAULT NULL,`comment` varchar(255) DEFAULT NULL,`year_publication` year(4) NOT NULL,UNIQUE KEY `UniqIdx` (`bookid`),KEY `bkcmtIdex` (`comment`),KEY `BKAuthAndInfoIdex` (`authors`(30),`info`(50))
) ENGINE=InnoDB DEFAULT CHARSET=gb2312
1 row in set (0.00 sec)mysql>

添加AUTO_INCREMENT 的约束字段的唯一索引不能删除

2.用DROP INDEX删除

mysql> drop index BKAuthAndInfoIdex on book1;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql> show create table book1\G
*************************** 1. row ***************************Table: book1
Create Table: CREATE TABLE `book1` (`bookid` int(11) NOT NULL,`bookname` varchar(255) NOT NULL,`authors` varchar(255) NOT NULL,`info` varchar(255) DEFAULT NULL,`comment` varchar(255) DEFAULT NULL,`year_publication` year(4) NOT NULL,UNIQUE KEY `UniqIdx` (`bookid`),KEY `bkcmtIdex` (`comment`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312
1 row in set (0.00 sec)mysql>

删除表中的列时,如果要删除的列为索引的组成部分,则该列也会从索引中删除。如果组成索引的所有列都被删除,那么整个索引将被删除。
这只是我的一些浅薄的见解,望多指教!

(六)MySQL索引相关推荐

  1. MySQL索引面试题六连击

    MySQL索引面试题六连击 最近在微信公众号上看到一篇推文,关于MySQL索引面试题的,觉得写得挺好,整理了一下形成博客总结. 原文链接:关于MySQL索引面试题的6连炮!招架的住吗? 1.面试真题 ...

  2. mysql调优(六)--索引的基础知识

    思维导图 一.索引的优点 1.大大减少了服务器需要扫描的数据量. 2.帮助服务器避免排序和临时表. 3.将随机io变成顺序io. 问题一.什么是随机io和顺序io. 顺序IO是指读写操作的访问地址连续 ...

  3. 带你了解什么是MySQL数据库(六)索引原理,如何建立与使用索引

    文章目录 前言 索引原理 介绍 查找二叉树.平衡二叉树.B树.B+树 聚集索引与非聚集索引 索引管理 测试索引 正确使用索引 联合索引 索引下推技术 索引优化神器 常见慢查询优化 前言 学习过某一门编 ...

  4. mysql索引(六)主键索引

    Mysql索引大概有五种类型: 普通索引(INDEX):最基本的索引,没有任何限制 唯一索引(UNIQUE):与"普通索引"类似,不同的就是:索引列的值必须唯一,但允许有空值. 主 ...

  5. mysql json匹配key为数值_干货篇:一篇文章让你——《深入解析MySQL索引原理》

    概述 最近一段时间重新深入研究了一遍MySQL的内容,今天主要分享分析MySQL索引原理,后续会输出一些关于MySQL方面的干货,希望各位小伙伴喜欢. 一.什么是索引.为什么要建立索引? 关于索引的理 ...

  6. Mysql 索引原理及优化

    本文内容主要来源于互联网上主流文章,只是按照个人理解稍作整合,后面附有参考链接. 一.摘要 本文以MySQL数据库为研究对象,讨论与数据库索引相关的一些话题.特别需要说明的是,MySQL支持诸多存储引 ...

  7. MySQL索引背后的数据结构及算法原理--转

    MySQL索引背后的数据结构及算法原理 作者 张洋 | 发布于 2011-10-18 MySQL 索引 B树 优化 原文地址:http://blog.codinglabs.org/articles/t ...

  8. MYSQL:MYSQL索引为什么选择B+树?

    带有顺序访问指针的B+Tree 一般在数据库系统或文件系统中使用的B+Tree结构都在经典B+Tree的基础上进行了优化,增加了顺序访问指针. 图4 如图4所示,在B+Tree的每个叶子节点增加一个指 ...

  9. mysql索引数据结构图解_深入理解Mysql索引底层数据结构与算法

    索引的定义:索引(Index)是帮助MySQL高效获取数据的数据结构. Q1:大家使用索引有没有想过这个问题?为什么索引能够帮助mysql高效获取数据?我一一给大家道来!在给大家讲之前,先更大家分享一 ...

最新文章

  1. 最小生成树算法详解(prim+kruskal)
  2. 【Android 组件化】路由组件 ( 注解处理器调试 )
  3. 经典常用算法/常用算法思维---附伪代码以及实现
  4. sklearn输出模型参数_如何使用sklearn优雅地进行数据挖掘?
  5. 哥大计算机工程申请入口和登陆入口
  6. P3345-[ZJOI2015]幻想乡战略游戏【点分树,RMQ】
  7. hashmap value占用空间大小_HashMap的put和get实现原理及源码分析
  8. ldap认证服务的搭建
  9. 与微信同行近 8 年,49 岁的张小龙去哪儿了?
  10. 路径规划之空间采样算法研究现状简述
  11. oracle修改只读数据库中,如何在oracle中创建只读数据库链接
  12. GULP案例1:计算声子色散曲线和态密度
  13. Python数据处理Tips数据特征处理离散化和二值化
  14. 企业运维实践-Nginx使用geoip2模块并利用MaxMind的GeoIP2数据库实现处理不同国家或城市的访问最佳实践指南...
  15. VIJOS-P1625 精卫填海(背包)
  16. 动态规划-最短路径问题
  17. css给div四角添加效果
  18. 暑假假期训练总结-26
  19. nRF24l01无线传输
  20. 项目需求说明书中的假定和约束

热门文章

  1. 《牛津字典精华总结》- 初阶系列 - 字母 - M
  2. 2022年了,你在用哪些Mac软件?
  3. 我是懒癌患者,谈不上996
  4. java——集合——Map集合——Map集合遍历键找值方式
  5. AutoCAD线条加粗秘诀
  6. jar通用shell启停脚本
  7. ps photoshop,如何做出太阳光放射的效果,如图
  8. Download interrupted: Read timed out问题解决方案集
  9. 2023年江苏专转本考试政策
  10. 虚拟机修改服务器时间,ESXI 6.7系统时间不对,影响内部虚拟机时间,修复及修改方法分享...