search
HomeDatabaseMysql TutorialMySQL笔记之索引的使用_MySQL

MySQL笔记之索引的使用_MySQL

Jun 01, 2016 pm 01:24 PM
informationDatabase systemsDatabase TableRecord

bitsCN.com

索引是创建在表上的,对数据库表中一列或多列的值进行排序的一种结构

其作用主要在于提高查询的速度,降低数据库系统的性能开销

通过索引,查询数据不必读完记录的全部信息进行匹配,而是只查询索引列

索引相当于字典中的音序表,要查询某字时可以在音序表中找到

然后直接跳转到那一音序所在位置,而不必从字典第一页开始翻,逐字匹配

tips:索引虽能提高查询速度,但在插入记录时会按照索引进行排序,因此降低了插入速度

     最好的操作方式是先删除索引,插入大量记录后再创建索引


索引分类

1.普通索引:不附加任何限制条件,可创建在任何数据类型中

2.唯一性索引:使用unique参数可以设置索引为唯一性索引,在创建索引时,限制该索引的值必须唯一,主键就是一种唯一性索引

3.全文索引:使用fulltext参数可以设置索引为全文索引。全文索引只能创建在char、varchar或text类型的字段上。查询数据量较大的字符串类型字段时,效果明显。但只有MyISAM存储引擎支持全文检索

4.单列索引:在表中单个字段上创建的索引,单列索引可以是任何类型,只要保证索引只对应一个一个字段

5.多列索引:在表中多个字段上创建的索引,该索引指向创建时对应的多个字段

6.空间索引:使用spatial参数可以设置索引为空间索引,空间索引只能建立在空间数据类型上比如geometry,并且不能为空,目前只有MyISAM存储引擎支持


在创建表时创建索引
创建普通索引

mysql> create table index1(
    -> id int,
    -> name varchar(20),
    -> sex boolean,
    -> index(id)
    -> );
Query OK, 0 rows affected (0.11 sec)

此处在id字段上创建索引,show create table可查看


创建唯一性索引

mysql> create table index2(
    -> id int unique,
    -> name varchar(20),
    -> unique index index2_id(id ASC)
    -> );
Query OK, 0 rows affected (0.12 sec)

此处使用id字段创建了一个名为index2_id的索引

这里的id字段可以不设置唯一性约束,但这样一来索引就没有作用


创建全文索引

mysql> create table index3(
    -> id int,
    -> info varchar(20),
    -> fulltext index index3_info(info)
    -> )engine=MyISAM;
Query OK, 0 rows affected (0.07 sec)

要注意创建全文索引时只能使用MyISAM存储引擎


创建单列索引

mysql> create table index4(
    -> id int,
    -> subject varchar(30),
    -> index index4_st(subject(10))
    -> );
Query OK, 0 rows affected (0.12 sec)

此处subject字段长度是30,而索引长度则是10

这么做的目的在于提高查询速度,对于字符型的数据不用查询全部信息


创建多列索引

mysql> create table index5(
    -> id int,
    -> name varchar(20),
    -> sex char(4),
    -> index index5_ns(name,sex)
    -> );
Query OK, 0 rows affected (0.10 sec)

可以看出,这里使用了name字段和sex字段创建索引列


创建空间索引

mysql> create table index6(
    -> id int,
    -> space geometry not null,
    -> spatial index index6_sp(space)
    -> )engine=MyISAM;
Query OK, 0 rows affected (0.07 sec)

这里需要注意空间space字段不能为空,还有存储引擎


在已经存在的表上创建索引
创建普通索引

mysql> create index index7_id on example0(id);
Query OK, 0 rows affected (0.07 sec)
Records: 0  Duplicates: 0  Warnings: 0

这里在现有表的id字段上创建了一条名为index7_id的索引


创建唯一性索引

mysql> create unique index index8_id on example1(course_id);
Query OK, 0 rows affected (0.16 sec)
Records: 0  Duplicates: 0  Warnings: 0

此处只需要在index关键字前面加上unique即可

至于表中的course_id字段,最要也设置唯一性约束条件


创建全文索引

mysql> create fulltext index index9_info on example2(info);
Query OK, 0 rows affected (0.07 sec)
Records: 0  Duplicates: 0  Warnings: 0

fulltext关键字用来设置全文引擎,此处的表必须是MyISAM存储引擎


创建单列索引

mysql> create index index10_addr on example3(address(4));
Query OK, 0 rows affected (0.16 sec)
Records: 0  Duplicates: 0  Warnings: 0

此表中address字段的长度是20,这里只查询4字节,不需要全部查询


创建多列索引

mysql> create index index11_na on example4(name,address);
Query OK, 0 rows affected (0.16 sec)
Records: 0  Duplicates: 0  Warnings: 0

索引创建好之后,查询中必须有name字段才能使用


创建空间索引

mysql> create spatial index index12_line on example5(space);
Query OK, 0 rows affected (0.07 sec)
Records: 0  Duplicates: 0  Warnings: 0

这里需要注意存储引擎是MyISAM,还有空间数据类型

用alter table语句来创建索引
创建普通索引

mysql> alter table example6 add index index13_n(name(20));
Query OK, 0 rows affected (0.16 sec)
Records: 0  Duplicates: 0  Warnings: 0


创建唯一性索引

mysql> alter table example7 add unique index index14_id(id);
Query OK, 0 rows affected (0.20 sec)
Records: 0  Duplicates: 0  Warnings: 0


创建全文索引

mysql> alter table example8 add fulltext index index15_info(info);
Query OK, 0 rows affected (0.08 sec)
Records: 0  Duplicates: 0  Warnings: 0


创建单列索引

mysql> alter table example9 add index index16_addr(address(4));
Query OK, 0 rows affected (0.16 sec)
Records: 0  Duplicates: 0  Warnings: 0


创建多列索引

mysql> alter table example10 add index index17_in(id,name);
Query OK, 0 rows affected (0.16 sec)
Records: 0  Duplicates: 0  Warnings: 0


创建空间索引

mysql> alter table example11 add spatial index index18_space(space);
Query OK, 0 rows affected (0.06 sec)
Records: 0  Duplicates: 0  Warnings: 0

到此,三种操作方式,每种索引类别的建立就都列举了

对于索引,重要的是理解索引的概念,明白索引的种类

更多的是自己的使用经验

最后来看看索引的删除


删除索引

mysql> drop index index18_space on example11;
Query OK, 0 rows affected (0.08 sec)
Records: 0  Duplicates: 0  Warnings: 0

这里是刚刚创建的一条索引

其中index18_space是索引名,example11是表名

bitsCN.com
Statement
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
MySQL: An Introduction to the World's Most Popular DatabaseMySQL: An Introduction to the World's Most Popular DatabaseApr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

The Importance of MySQL: Data Storage and ManagementThe Importance of MySQL: Data Storage and ManagementApr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system suitable for data storage, management, query and security. 1. It supports a variety of operating systems and is widely used in Web applications and other fields. 2. Through the client-server architecture and different storage engines, MySQL processes data efficiently. 3. Basic usage includes creating databases and tables, inserting, querying and updating data. 4. Advanced usage involves complex queries and stored procedures. 5. Common errors can be debugged through the EXPLAIN statement. 6. Performance optimization includes the rational use of indexes and optimized query statements.

Why Use MySQL? Benefits and AdvantagesWhy Use MySQL? Benefits and AdvantagesApr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Apr 12, 2025 am 12:16 AM

InnoDB's lock mechanisms include shared locks, exclusive locks, intention locks, record locks, gap locks and next key locks. 1. Shared lock allows transactions to read data without preventing other transactions from reading. 2. Exclusive lock prevents other transactions from reading and modifying data. 3. Intention lock optimizes lock efficiency. 4. Record lock lock index record. 5. Gap lock locks index recording gap. 6. The next key lock is a combination of record lock and gap lock to ensure data consistency.

What are common causes of poor MySQL query performance?What are common causes of poor MySQL query performance?Apr 12, 2025 am 12:11 AM

The main reasons for poor MySQL query performance include not using indexes, wrong execution plan selection by the query optimizer, unreasonable table design, excessive data volume and lock competition. 1. No index causes slow querying, and adding indexes can significantly improve performance. 2. Use the EXPLAIN command to analyze the query plan and find out the optimizer error. 3. Reconstructing the table structure and optimizing JOIN conditions can improve table design problems. 4. When the data volume is large, partitioning and table division strategies are adopted. 5. In a high concurrency environment, optimizing transactions and locking strategies can reduce lock competition.

When should you use a composite index versus multiple single-column indexes?When should you use a composite index versus multiple single-column indexes?Apr 11, 2025 am 12:06 AM

In database optimization, indexing strategies should be selected according to query requirements: 1. When the query involves multiple columns and the order of conditions is fixed, use composite indexes; 2. When the query involves multiple columns but the order of conditions is not fixed, use multiple single-column indexes. Composite indexes are suitable for optimizing multi-column queries, while single-column indexes are suitable for single-column queries.

How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)Apr 10, 2025 am 09:36 AM

To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

MySQL and SQL: Essential Skills for DevelopersMySQL and SQL: Essential Skills for DevelopersApr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.