What is a mysql index? Introduction to related knowledge of mysql index
This article brings you what is the mysql index? The introduction of relevant knowledge about mysql index has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
What is an index
The index is like the table of contents of a book
The index is used for quick search To find a row with a specific value in a column, without using an index, MySQL must read the entire table starting from the first record until it finds the relevant row. The larger the table, the more time it takes to query the data. If the queried column in the table has an index, MySQL can quickly get to a location to search the data file without having to look at all the data, which will save a lot of time.
Advantages and Disadvantages
Advantages
1. Greatly speed up querying
2. All field types can be indexed
Disadvantages
1. It takes time to create and maintain indexes. The more data, the more time-consuming
2. Indexes occupy storage space, and the data in the data table will also There is a maximum online setting. If we have a large number of indexes, the index file may reach the online value faster than the data file
3. When adding, deleting, or modifying data in the table, the index also needs Dynamic maintenance reduces the data maintenance speed
Usage principles and scenarios
1. The more indexes, the better, it depends on the situation
2. Frequently updated tables should have as few indexes as possible
3. Construct indexes for fields that are frequently used for queries
4. Try not to use indexes for fields with small amounts of data. Query all The time spent on data is shorter than that of traversing the index data, and the index will have no optimization effect
5. Try not to use indexes for fields with few different values, such as the gender field which only has two different values for men and women.
Index classification
Note: The index is implemented in the storage engine, which means that different storage engines will use different indexes
MyISAM and InnoDB storage engines: only support BTREE indexes, which means BTREE is used by default and cannot be replaced.
MEMORY/HEAP storage engines: supports HASH and BTREE indexes
1. Single column Index
An index only contains a single column, but there can be multiple single-column indexes in a table
1.1. Ordinary index
The basic index type in MySQL, no What restrictions are allowed to insert duplicate values and null values in the columns where the index is defined, purely to query the data faster.
1.2. Unique index
The value in the index column must be unique, but null values are allowed
1.3. Primary key index
is a Special unique index, no null values allowed
2. Combined index
An index created on a combination of multiple fields in the table, only in the query conditions The index will only be used when the left field of these fields is used. When using the combined index, follow the best left prefix rule
3. Full-text index
Full-text index, It can only be used on the MyISAM engine, and full-text indexes can only be used on CHAR, VARCHAR, and TEXT type fields. Full-text index means that in a pile of text, you can find the record line to which the field belongs through a certain keyword, for example, "You are a big bad pen, a second-rate person..." Through the big bad pen, it may be possible Find the record
4. Spatial index
The spatial index is an index established for fields of spatial data types. There are four spatial data types in MySQL, GEOMETRY , POINT, LINESTRING, POLYGON. When creating a spatial index, use the SPATIAL keyword. Requirements: The engine is MyISAM. The column used to create a spatial index must be declared as NOT NULL
Index method
Usage principle: If the difference in values is large, and Mainly based on equal value search (=, , in), Hash index is a more efficient choice, it has O(1) search complexity; if the difference of values is relatively poor, and range search is Mainly, B-tree is a better choice, it supports range search.
B-Tree Index
B-Tree index has the capabilities of range search and prefix search. For a B-tree with N nodes, the complexity of retrieving a record is O(LogN). Equivalent to binary search.
Hash Index
Hash index can only perform equal searches, but no matter how big the Hash table is, the search complexity is O(1).
Index creation and deletion
Creation
Created when creating a table
CREATE TABLE 表名[字段名 数据类型] [UNIQUE|FULLTEXT|SPATIAL|...] [INDEX|KEY] [索引名字] (字段名[length]) [ASC|DESC]
Example:
CREATE TABLE `NewTable` ( `id` INT NOT NULL AUTO_INCREMENT, `username` VARCHAR (255) NOT NULL, `name` VARCHAR (255) NOT NULL, `sex` TINYINT NOT NULL DEFAULT 0, `address` VARCHAR (255) NULL, PRIMARY KEY (`id`), # 主键索引 INDEX `name` (`name`) USING BTREE, # 普通索引 UNIQUE INDEX `username` (`username`) USING BTREE # 唯一索引 INDEX `u_n_a` (`username`, `name`,`address`) USING BTREE # 组合索引 );
Existing table creation
ALTER TABLE 表名 ADD[UNIQUE|FULLTEXT|SPATIAL] [INDEX|KEY] [索引名] (索引字段名)[ASC|DESC]
Example:
ALTER TABLE `test` ADD PRIMARY KEY (`id`), # 主键索引 ADD INDEX `name` (`name`) USING BTREE , # 普通索引 ADD UNIQUE INDEX `username` (`username`) USING BTREE , # 唯一索引 ADD INDEX `u_n_a` (`username`, `name`, `address`) USING BTREE ; # 组合索引
Delete index
ALTER TABLE 表名 DROP INDEX 索引名。
Example:
ALTER TABLE `test` DROP PRIMARY KEY, DROP INDEX `username`, DROP INDEX `name`, DROP INDEX `u_n_a`;
Update index
Delete first and then build
ALTER TABLE `test` DROP INDEX `username` , ADD UNIQUE INDEX `username1` (`username`) USING BTREE , DROP INDEX `name` , ADD INDEX `name2` (`name`) USING BTREE , DROP INDEX `u_n_a` , ADD INDEX `u_a_n` (`username`, `address`, `name`) USING BTREE ;
Index failure situation
1. The combined field does not follow the optimal left prefix rule
2. Fuzzy query, such as like '%test
# 索引生效 select * from `test` where `name` like "123"; # 索引生效 select * from `test` where `name` like "123%"; # 索引失效 select * from `test` where `name` like "%123"; # 索引失效 select * from `test` where `name` like "%123%";
3. 在索引列上做如下任何操作(计算,函数,(自动或者手动)类型装换),会导致索引失效而导致全表扫描
如 sex 字段上添加索引
# 索引失效 select * from `test` where `sex`*0.5 = 1
4. 范围索引(>,
构建索引
ALTER TABLE `test` ADD INDEX `s_n` (`sex`, `name`) USING BTREE ;
示例:
# 命中全部 select * from `test` where `sex` = 1 and `name` = 'a'; # 命中部分,sex命中,name失效 select * from `test` where `sex` > 1 and `name` = 'a';
5. !=, is null, is not null 无法使用索引
6. 字符串字段的值不加单引号(数字不报错,英文报错)索引失效
构建索引
ALTER TABLE `test` ADD INDEX `name` (`name`) USING BTREE ;
示例
# 索引失效 select * from `test` where `name` = 123; # 索引生效 select * from `test` where `name` = '123';
7. or 条件导致索引失效
构建索引
ALTER TABLE `test` ADD INDEX `sex` (`sex`) USING BTREE ; ADD INDEX `n_u` (`name`, `username`) USING BTREE ;
示例:
# 索引不生效 select * from `test` where (`name` = 'aa' and `username` = 'aa') or `sex` > 1 # 索引sex生效 select * from `test` where `sex` = 1 and (`id` = 2 or `name` = 'aa' )
附录
最佳左前缀法则
如果索引了多列,要遵守最左前缀法则。指的是查询要从索引的最左前列开始并且不跳过索引中的列
如下构建索引
ALTER TABLE `test` ADD INDEX `u_a_n` (`username`, `address`, `name`) USING BTREE ;
如下查询情况
# 命中部分 select * from `test` where `username` = 'aaa'; # 命中部分 select * from `test` where `username` = 'aa' and `address` = 'aaa'; # 全命中 select * from `test` where `username` = 'aa' and `address` = 'aaa' and `name` = 'a'; # 不命中,第一条件字段不是username select * from `test` where `address` = 'aaa';
The above is the detailed content of What is a mysql index? Introduction to related knowledge of mysql index. For more information, please follow other related articles on the PHP Chinese website!

ACID attributes include atomicity, consistency, isolation and durability, and are the cornerstone of database design. 1. Atomicity ensures that the transaction is either completely successful or completely failed. 2. Consistency ensures that the database remains consistent before and after a transaction. 3. Isolation ensures that transactions do not interfere with each other. 4. Persistence ensures that data is permanently saved after transaction submission.

MySQL is not only a database management system (DBMS) but also closely related to programming languages. 1) As a DBMS, MySQL is used to store, organize and retrieve data, and optimizing indexes can improve query performance. 2) Combining SQL with programming languages, embedded in Python, using ORM tools such as SQLAlchemy can simplify operations. 3) Performance optimization includes indexing, querying, caching, library and table division and transaction management.

MySQL uses SQL commands to manage data. 1. Basic commands include SELECT, INSERT, UPDATE and DELETE. 2. Advanced usage involves JOIN, subquery and aggregate functions. 3. Common errors include syntax, logic and performance issues. 4. Optimization tips include using indexes, avoiding SELECT* and using LIMIT.

MySQL is an efficient relational database management system suitable for storing and managing data. Its advantages include high-performance queries, flexible transaction processing and rich data types. In practical applications, MySQL is often used in e-commerce platforms, social networks and content management systems, but attention should be paid to performance optimization, data security and scalability.

The relationship between SQL and MySQL is the relationship between standard languages and specific implementations. 1.SQL is a standard language used to manage and operate relational databases, allowing data addition, deletion, modification and query. 2.MySQL is a specific database management system that uses SQL as its operating language and provides efficient data storage and management.

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

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.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor