1Select the data type of the index
MySQL supports many data types. Choosing the appropriate data type to store data has a great impact on performance. Generally speaking, some guidelines can be followed:
(1) Smaller data types are usually better: Smaller data types usually require less space on disk, memory, and CPU cache. Processing is faster.
(2) Simple data types are better: Integer data has less processing overhead than characters, because the comparison of strings is more complex. In MySQL, you should use the built-in date and time data types instead of strings to store time; and use integer data types to store IP addresses.
(3) Try to avoid NULL: the column should be specified as NOT NULL, unless you want to store NULL. In MySQL, columns containing null values are difficult to optimize queries because they complicate indexes, index statistics, and comparison operations. You should replace null values with 0, a special value, or an empty string.
2
Type of index
Index is implemented in the storage engine, not in the server layer. Therefore, the indexes of each storage engine are not necessarily exactly the same, and not all storage engines support all index types
(1) Ordinary index
This is the most basic index. It has no restrictions. It has the following creation methods:
Create index
CREATE INDEX indexName ON mytable(username(length)); If it is CHAR, VARCHAR type, length can be less than the actual length of the field; if it is For BLOB and TEXT types, length must be specified, the same below.
Modify the table structure
ALTER mytable ADD INDEX [indexName] ON (username(length)) ◆创建表的时候直接指定 CREATE TABLE mytable( ID INT NOT NULL, username VARCHAR(16) NOT NULL, INDEX [indexName] (username(length)) ); 删除索引的语法: DROP INDEX [indexName] ON mytable;
(2) Unique index
It is similar to the previous ordinary index, except that the value of the index column must be unique, but empty is allowed value. In the case of a composite index, the combination of column values must be unique. It has the following creation methods:
Create index
CREATE UNIQUE INDEX indexName ON mytable(username(length)) ◆修改表结构 ALTER mytable ADD UNIQUE [indexName] ON (username(length)) ◆创建表的时候直接指定 CREATE TABLE mytable( ID INT NOT NULL, username VARCHAR(16) NOT NULL, UNIQUE [indexName] (username(length)) );
(3) Primary key index
It is a special unique index that does not allow null values. Generally, the primary key index is created at the same time when creating the table:
CREATE TABLE mytable( ID INT NOT NULL, username VARCHAR(16) NOT NULL, PRIMARY KEY(ID) ); 当然也可以用 ALTER 命令。记住:一个表只能有一个主键。
(4) Composite index
In order to vividly compare the single column index and the composite index, add multiple fields to the table:
CREATE TABLE mytable( ID INT NOT NULL, username VARCHAR(16) NOT NULL, city VARCHAR(50) NOT NULL, age INT NOT NULL ); In order to further extract the efficiency of MySQL,
Consider creating a combined index. That is to build name, city, age into an index:
ALTER TABLE mytable ADD INDEX name_city_age (name(10),city,age); When creating the table, the usernname length is 16, and 10 is used here. This is because generally the name length will not exceed 10, which will speed up the index query, reduce the size of the index file, and improve the update speed of INSERT.
If you create single-column indexes on usernname, city, and age respectively, so that the table has three single-column indexes, the query efficiency will be very different from the above combined index, which is far lower than our combined index. . Although there are three indexes at this time, MySQL can only use the single-column index that it thinks is the most efficient.
Establishing such a combined index is actually equivalent to establishing the following three sets of combined indexes:
usernname,city,age usernname,city usernname Why is there no combined index like city,age? ? This is a result of the "leftmost prefix" of the MySQL composite index. The simple understanding is to only start the combination from the leftmost one. (This is one of the interview questions, and I should have answered it correctly at the time) Not only queries containing these three columns will use this combined index, but the following SQL will use this combined index:
SELECT FROM mytable WHREE username="admin" AND city="郑州" SELECT FROM mytable WHREE username="admin" 而下面几个则不会用到: SELECT FROM mytable WHREE age=20 AND city="郑州" SELECT FROM mytable WHREE city="郑州"
3
Time to create an index
Now we have learned how to create an index, so under what circumstances do we need to create an index? Generally speaking, columns appearing in WHERE and JOIN need to be indexed, but this is not entirely true, because MySQL only indexes , >=, BETWEEN, IN, and sometimes LIKE will use the index. For example:
SELECT t.Name FROM mytable t LEFT JOIN mytable m ON t.Name=m.username WHERE m.age=20 AND m.city='郑州' 此时就需要对city和age建立索引,由于mytable表的userame也出现在了JOIN子句中,也有对它建立索引的必要。
Just mentioned that only LIKE at certain times needs to be indexed. Because MySQL will not use the index when making queries starting with wildcard characters % and _. For example, the following sentence will use the index:
SELECT * FROM mytable WHERE username like'admin%' 而下句就不会使用: SELECT * FROM mytable WHEREt Name like'%admin' 因此,在使用LIKE时应注意以上的区别。
4
The shortcomings of the index
The above mentioned using the index Benefits, but excessive use of indexes can lead to abuse. Therefore, the index will also have its shortcomings:
Although the index greatly improves the query speed, it will also reduce the speed of updating the table, such as INSERT, UPDATE and DELETE on the table. Because when updating the table, MySQL not only needs to save the data, but also save the index file.
Creating index files will occupy disk space. Generally, this problem is not serious, but if you create multiple combined indexes on a large table, the index file will expand quickly.
Indexes are only one factor to improve efficiency. If your MySQL has a large amount of data tables, you need to spend time researching and building the best indexes, or optimizing query statements
5
Notes on using indexes
When using indexes, there are some tips and precautions:
The index will not contain columns with NULL values.
只要列中包含有NULL值都将不会被包含在索引中,复合索引中只要有一列含有NULL值,那么这一列对于此复合索引就是无效的。所以我们在数据库设计时不要让字段的默认值为NULL。
使用短索引
对串列进行索引,如果可能应该指定一个前缀长度。例如,如果有一个CHAR(255)的列,如果在前10个或20个字符内,多数值是惟一的,那么就不要对整个列进行索引。短索引不仅可以提高查询速度而且可以节省磁盘空间和I/O操作。
索引列排序
MySQL查询只使用一个索引,因此如果where子句中已经使用了索引的话,那么order by中的列是不会使用索引的。因此数据库默认排序可以符合要求的情况下不要使用排序操作;尽量不要包含多个列的排序,如果需要最好给这些列创建复合索引。
like语句操作
一般情况下不鼓励使用like操作,如果非使用不可,如何使用也是一个问题。like “%aaa%” 不会使用索引而like “aaa%”可以使用索引。
不要在列上进行运算
select * from users where YEAR(adddate)<2015; 将在每个行上进行运算,这将导致索引失效而进行全表扫描,因此我们可以改成 select * from users where adddate<‘2015-01-01’;
不使用NOT IN和操作
以上就是MySQL索引类型与优缺点的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

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.

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.

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

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.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Chinese version
Chinese version, very easy to use
