当前位置:网站首页>[MySQL] - index principle and use
[MySQL] - index principle and use
2022-07-26 22:36:00 【Envy ˇ】
Preface
I'm learning mysql In the process of , I believe most students are building tables and querying tables , I don't know mysql How to find these data through our given conditions , Index is an important feature of quickly finding data , Then let's introduce
Catalog
Why is there an index ? What is the index ?
The advantages and disadvantages of indexing
The leftmost prefix principle of Composite Index
The principle of index creation
The data structure of the index
Clustered index and non clustered index
Why is there an index ? What is the index ?
mysql Stored data is Store by page Of , That is, the stored data page by page , If there is 1 Ten thousand data ( If points 10 page ), At this time, we go to find No 9000 Data , Then start with the first data on the first page and look back in turn , We can see that , This search is quite slow , But if there is a page number at this time , 9000 Article corresponds to article 9 page , We can start from 9 Start looking for , Is this a lot more efficient
But the index we are talking about here is not like the index in the array , there An index is a data structure (InnoDB The engine uses B+ Trees ), Help us get data efficiently , So the database not only stores data , It also maintains such a data structure to help us get these data quickly
The advantages and disadvantages of indexing
advantage
The advantage of indexing is obvious , It speeds up our data acquisition , Increase of efficiency , Reduces database costs IO Cost of , You can sort the data by index columns , Reduce the cost of sorting data , To reduce the CPU Consumption of
Inferiority
The index here is a data structure , That means we need to maintain such a data structure alone , So indexing increases the overhead , And if we write data ( Add, delete, modify ) When , Indexes also change , At this time, it is not only necessary to maintain data , Also maintain the index
So we usually decide the use of the index according to the actual situation
Classification of indexes
mysql Different index types are defined according to our different requirements
primary key
When we set a field in the table as the primary key , The database will be automatically indexed , The primary key is the unique identifier of the table , It is suitable for indexing
ALTER TABLE Table name add PRIMARY KEY Table name ( Name );
-- Delete the primary key index :
ALTER TABLE Table name drop PRIMARY KEY ;Single value index
An index contains only a single column , A table can have multiple single valued indexes , Of course, in addition to the primary key , We can also create indexes through other fields of the table
-- Create a single value index
CREATE INDEX Index name ON Table name ( Name );
-- Delete index :
DROP INDEX Index name ;unique index
The unique index is also relative to the column , But it requires that the data in this column cannot be repeated , It can be for null
CREATE UNIQUE INDEX Index name ON Table name ( Name );
-- Delete index
DROP INDEX Index name ON Table name ;Composite index ( Composite index )
An index contains multiple columns , Its creation cost is less , Relative to single valued index , Generally, composite indexes are used when there are many data in the table ( The number of rows in the table is much larger than the number of index columns )
-- Create composite index
CREATE INDEX Index name ON Table name ( Column 1, Column 2...);
-- Delete index :
DROP INDEX Index name ON Table name ;The leftmost prefix principle of Composite Index
When using composite indexes , Need to meet such a principle : When using the column of the composite index as the condition , The leftmost column must appear as a condition , Otherwise, the combined index will not take effect .
Examples are as follows : Table has a,b,c 3 Column , by a,b Create a composite index with two columns
Columns such as select * from table where a=’’and b=’’ The index works
select * from table where b=’’and a=’’ The index works
select * from table where a=’’and c=’’ The index works
select * from table where b=’’and c=’’ Index does not work
Full-text index
When we use fuzzy queries , Use like when , At this time, the general index is invalid , At this time, we need to use full-text indexing
-- Create full text index
CREATE FULLTEXT INDEX Index name ON Table name ( Field name ) WITH PARSER ngram;
-- Fuzzy query
SELECT structure FROM Table name WHERE MATCH( Name ) AGAINST( Search terms ')The principle of index creation
After recognizing the characteristics of index , So imagine , In which case do we need to use indexes , Or not using indexes ? Summarized below
Need index
First of all, the primary key automatically establishes a unique index , In addition, fields frequently used as query criteria should also be indexed (where The following sentence ) , Fields associated with other tables in the query , Foreign key relationships create indexes , Sort in query , Grouped fields , These are in order , Grouped fields are more efficient to find by index
There is no need to index
Tables with less data in the table , If there is little data in the table , Then we don't need to use indexes at all , Another is the table that is frequently added, deleted and modified , When we write data , The index will also change , So this maintenance will affect the efficiency . where Do not create an index for fields that are not used after the condition , A table whose data is repeated and evenly distributed , Duplicate data columns , Indexing is not very effective
The data structure of the index
mysql The default storage engine is InnoDB, It uses B+ The data structure implemented by the tree as an index
Mysql The index uses B+ Trees , Because indexes are used to speed up queries , and B+ The tree can improve the query speed by sorting the data , Then multiple elements can be stored in one node , So that B+ The height of the tree will not be too high . And there are pointers between leaf nodes , It can well support full table scanning , Scope search, etc SQL sentence .

Clustered index and non clustered index
Cluster index
Clustered index refers to : Find the index and find the data , A primary key is a clustered index
Nonclustered index
Non clustered index refers to : Find index first , No data is found at this time , Because the index and data are stored separately , After finding the index, we need to query the table again according to the index information , To find the data you need , It's also called secondary index
An example of this is as follows : Set up a student table
CREATE TABLE student (
id BIGINT,
NO VARCHAR (20),
NAME VARCHAR (20),
PRIMARY KEY (`id`),
UNIQUE KEY `idx_no` (`no`)
)Then we do three kinds of queries :
1. Get data through the primary key , Because the primary key is the unique identifier , So you can get all the data directly according to the primary key , It's a clustered index
2. Look up the number and name according to the number , The number itself is a unique index , But the query column contains the student number and student name , When the number index is hit , The primary key is stored in the data of the node of the index ID, According to the primary key ID Check again , So this kind of inquiry no Not clustered index
3. Check the number according to the number ( Determine whether the number exists ) , In this case , Return the number directly , Because the data needed is the index , No need to return table query , In this case no It's a clustered index .
stay mysql The default storage engine for InnoDB in , Data and index are stored together , It's a clustered design ( But it uses non clustered indexes ), And in the MYISAM In the engine , Data and index are stored separately , Yes no clustering design
边栏推荐
- Jd.com won the highest award for intelligent science and technology in China! Inventory JD system intelligent technology
- IDEA的那些环境配置及插件
- DAO 的发展状态
- Inventory of financial institutions
- Leetcode:857. Minimum cost of employing K workers [think in blocks + start with simplicity]
- 『Mysql』汇总Mysql索引失效的常见场景
- Implementation of V-model syntax sugar
- : could not determine a constructor for the tag ! RootAdmin
- 参数解析与跳石板
- Write golang simple C2 remote control based on grpc
猜你喜欢

Financial institution map

VCS编译、仿真过程

Write golang simple C2 remote control based on grpc

APP信息侦察&夜神模拟器Burp抓包配置

Implementation principle of semaphore in golang

2018 arXiv preprint | MolGAN: An implicit generative model for small molecular graphs

nvidia-smi报错:NVIDIA-SMI has failed because it couldn‘t communicate with the NVIDIA driver 完整记录

三星Galaxy Z可折叠产品的预告片泄露:'柔性好于平面'

The trailer of Samsung Galaxy Z foldable product leaked: 'flexibility is better than plane'

Cached database for memcached
随机推荐
LeetCode 122:买卖股票的最佳时机 II
The PRI that Hillhouse joined, including Junlian, Huakong, Shengshi, Lvdong and other 100 institutions, was killed
《强化学习周刊》第55期:LB-SGD、MSP-DRL & 对抗鲁棒强化学习
顺序表实现
The potential of emerging markets is unlimited, and advance.ai risk control products help Chinese offshore enterprises build a solid foundation for safe development
SQL二次注入详解
功耗降低、功能升级!启英泰伦发布二代语音AI芯片:模组价格低至14.99元!
NVIDIA SMI error: NVIDIA SMI has failed because it could't communicate with the NVIDIA driver complete record
Classification of banking business
蔚来杯2022牛客暑期多校训练营1
VCs compilation and simulation process
Chapter 15 MySQL user management
华为密谋收购巴西运营商?
Do you know why to design test cases after learning so long about use case design
Five years after graduation, I changed from information management to software testing engineer, and my monthly salary finally exceeded 12K
[paper reading] logan:membership influence attacks against generative models
Parameter analysis and stone jumping board
2022年最新西藏建筑安全员模拟题库及答案
Arduino实验一:双色灯实验
7.27抢先看 | openEuler 志高远,开源汇智创未来-开放原子全球开源峰会欧拉分论坛最详细议程出炉