search
HomeDatabaseMysql Tutorial所用MySQL索引类型的应用与创建

所用MySQL索引类型的应用与创建

Jun 07, 2016 pm 04:09 PM
mysqlmaincreateapplicationarticletypeindex

以下的文章主要描述的是MySQL索引类型,MySQL索引一共可以分为5中不同类型,以下的文章就是对正5种索引的具体应用以及实际创建方式的描述,希望会给你带来一些帮助在MySQL索引类型方面。 (1)MySQL索引类型:普通索引 这是最基本的索引,它没有任何限制。它有

以下的文章主要描述的是MySQL索引类型,MySQL索引一共可以分为5中不同类型,以下的文章就是对正5种索引的具体应用以及实际创建方式的描述,希望会给你带来一些帮助在MySQL索引类型方面。
 

(1)MySQL索引类型:普通索引

这是最基本的索引,它没有任何限制。它有以下几种创建方式:

创建索引

<ol class="dp-xml"><li class="alt"><span><span>CREATE INDEX indexName ON mytable(username(length)); </span></span></li></ol>

如果是CHAR,VARCHAR类型,length可以小于字段实际长度;如果是BLOB和TEXT类型,必须指定 length,下同。

修改表结构

<ol class="dp-xml"><li class="alt"><span><span>ALTER mytable ADD INDEX [indexName] ON (username(length)) </span></span></li></ol>

创建表的时候直接指定

<ol class="dp-xml"><li class="alt"><span><span>CREATE TABLE mytable( ID INT NOT NULL, username <br>VARCHAR(16) NOT NULL, INDEX [indexName] (username(length)) ); </span></span></li></ol>

删除索引的语法:

<ol class="dp-xml"><li class="alt"><span><span>DROP INDEX [indexName] ON mytable; </span></span></li></ol>

(2)MySQL索引类型:唯一索引

它与前面的普通索引类似,不同的就是:索引列的值必须唯一,但允许有空值。如果是组合索引,则列值的组合必须唯一。它有以下几种创建方式:

创建索引

<ol class="dp-xml"><li class="alt"><span><span>CREATE UNIQUE INDEX indexName ON mytable(username(length)) </span></span></li></ol>

修改表结构

<ol class="dp-xml"><li class="alt"><span><span>ALTER mytable ADD UNIQUE [indexName] ON (username(length)) </span></span></li></ol>

创建表的时候直接指定

<ol class="dp-xml"><li class="alt"><span><span>CREATE TABLE mytable( ID INT NOT NULL, <br>username VARCHAR(16) NOT NULL, UNIQUE [indexName] (username(length)) ); </span></span></li></ol>

(3)MySQL索引类型:主键索引

它是一种特殊的唯一索引,不允许有空值。一般是在建表的时候同时创建主键索引:

<ol class="dp-xml"><li class="alt"><span><span>CREATE TABLE mytable( ID INT NOT NULL, username VARCHAR(16) NOT NULL, PRIMARY KEY(ID) ); </span></span></li></ol>

当然也可以用 ALTER 命令。记住:一个表只能有一个主键。

(4)MySQL索引类型:组合索引

为了形象地对比单列索引和组合索引,为表添加多个字段:

<ol class="dp-xml"><li class="alt"><span><span>CREATE TABLE mytable( ID INT NOT NULL, username VARCHAR(16) NOT NULL, <br>city VARCHAR(50) NOT NULL, age INT NOT NULL ); </span></span></li></ol>

为了进一步榨取MySQL的效率,就要考虑建立组合索引。就是将 name, city, age建到一个索引里:

<ol class="dp-xml"><li class="alt"><span><span>ALTER TABLE mytable ADD INDEX name_city_age (name(10),city,age); </span></span></li></ol>

建表时,usernname长度为 16,这里用 10。这是因为一般情况下名字的长度不会超过10,这样会加速索引查询速度,还会减少索引文件的大小,提高INSERT的更新速度。

如果分别在 usernname,city,age上建立单列索引,让该表有3个单列索引,查询时和上述的组合索引效率也会大不一样,远远低于我们的组合索引。虽然此时有了三个索引,但MySQL只能用到其中的那个它认为似乎是最有效率的单列索引。

建立这样的组合索引,其实是相当于分别建立了下面三组组合索引:

<ol class="dp-xml"><li class="alt"><span><span>usernname,city,age usernname,city usernname </span></span></li></ol>

为什么没有 city,age这样的组合索引呢?

这是因为MySQL组合索引“最左前缀”的结果。简单的理解就是只从最左面的开始组合。并不是只要包含这三列的查询都会用到该组合索引,下面的几个SQL就会用到这个组合索引:

<ol class="dp-xml"><li class="alt"><span><span>SELECT * FROM mytable WHREE </span><span class="attribute">username</span><span>=</span><span class="attribute-value">"admin"</span><span> AND </span><span class="attribute">city</span><span>=</span><span class="attribute-value">"郑州"</span><span> <br>SELECT * FROM mytable WHREE </span><span class="attribute">username</span><span>=</span><span class="attribute-value">"admin"</span><span> </span></span></li></ol>

而下面几个则不会用到:

<ol class="dp-xml"><li class="alt"><span><span>SELECT * FROM mytable WHREE </span><span class="attribute">age</span><span>=</span><span class="attribute-value">20</span><span> AND </span><span class="attribute">city</span><span>=</span><span class="attribute-value">"郑州"</span><span> <br>SELECT * FROM mytable WHREE </span><span class="attribute">city</span><span>=</span><span class="attribute-value">"郑州"</span><span> </span></span></li></ol>

(5)MySQL索引类型:建立索引的时机

到这里我们已经学会了建立索引,那么我们需要在什么情况下建立索引呢?一般来说,在WHERE和JOIN中出现的列需要建立索引,但也不完全如此,因为MySQL只对,>=,BETWEEN,IN,以及某些时候的LIKE才会使用索引。例如:

<ol class="dp-xml"><li class="alt"><span><span>SELECT t.Name FROM mytable t LEFT JOIN mytable m ON </span><span class="attribute">t.<br>Name</span><span>=m.username WHERE </span><span class="attribute">m.age</span><span>=</span><span class="attribute-value">20</span><span> AND </span><span class="attribute">m.city</span><span>=</span><span class="attribute-value">'郑州'</span><span> </span></span></li></ol>

此时就需要对city和age建立索引,由于mytable表的userame也出现在了JOIN子句中,也有对它建立索引的必要。

刚才提到只有某些时候的LIKE才需建立索引。因为在以通配符%和_开头作查询时,MySQL不会使用索引。例如下句会使用索引:

<ol class="dp-xml"><li class="alt"><span><span>SELECT * FROM mytable WHERE username like'admin%' </span></span></li></ol>

而下句就不会使用:

<ol class="dp-xml"><li class="alt"><span><span>SELECT * FROM mytable WHEREt Name like'%admin' </span></span></li></ol>

以上的相关内容就是对MySQL索引类型的介绍,望你能有所收获。
 


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
How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

How to use MySQL functions for data processing and calculationHow to use MySQL functions for data processing and calculationApr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

An efficient way to batch insert data in MySQLAn efficient way to batch insert data in MySQLApr 29, 2025 pm 04:18 PM

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

Steps to add and delete fields to MySQL tablesSteps to add and delete fields to MySQL tablesApr 29, 2025 pm 04:15 PM

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor