当前位置:网站首页>MySQL advanced - basic index and seven joins
MySQL advanced - basic index and seven joins
2022-06-30 18:10:00 【Noblegasesgoo】
What is? MySQL Indexes
- Index is help MySQL Efficient access to data data structure ( Orderly ), It can be understood as a sorted fast search data structure .
- Out of data , The database system also maintains Data structures that satisfy specific search algorithms , These data structures are referenced in some way ( Point to ) data , In this way, we can use these data structures Implement advanced search algorithm , This data structure is the index .
- We usually say MySQL Index in , If not specified , All refer to BTree( Multiple search trees , It doesn't have to be a binary ) Index of structural organization . among Clustered index , Secondary index , Overlay index , Composite index , Prefix index , unique index The default is to use B+Tree(BTree A kind of ), Collectively, index . except B+Tree Outside of this type of index , And hash index .
- Generally speaking , The index itself is quite large , It's impossible to store everything in memory , therefore , Indexes are often stored on disk in the form of index files (.idx)
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-PnSoLBLx-1644828609425)(2021-11-26-MySQL Index in .assets/image-20211126130332023.png)]](/img/20/0696c0cbb31be67ba603dbd16ae2a6.jpg)
- Analyze the picture above :
On the left is the data table , There are two columns of seven data , The leftmost hexadecimal digit represents their physical address ( Logically adjacent , But the disks are not necessarily adjacent ). In order to speed up Col2 Lookup , You can maintain a binary lookup tree shown on the right to speed up data access .
The advantages and disadvantages of index
advantage
It's like a catalog index of books , It improves the efficiency of data retrieval , Data retrieval , Every time we traverse, we have to read from disk to memory , The index reduces the number of iterations , So index Reduce the database of IO cost ( influence WHERE).
Sort data through index columns , Reduce the cost of sorting data , Reduce CPU Consumption of ( influence ORDER BY).
Inferiority
- An index is essentially a table , This table holds the primary key in the index field , And point to the record of the entity class , So index columns also need to occupy space , So we usually put it on disk instead of memory .
- Indexes Greatly improve the query efficiency , along with it It reduces the speed of updating tables , For example, we add, delete and modify , Will affect the correspondence in the index table .
The structure of the index
Index he is MySQL Of Storage engine layer Implemented in , Not in Server layer Realized . therefore The index of each storage engine is not necessarily the same , At the same time, not all storage engines can support all index types .
- BTREE Indexes : The most common type of index , Most storage engines support , stay MySQL Of InnoDB engine Medium is BTREE Under the structure of B+Tree Index structure .
- HASH Indexes : The use scenario is simple .
- R-tree Indexes ( Spatial index ): The spatial index is MylSAM A special index type of the engine , Mainly used for geospatial data types , Usually used less .
- Full-text( Full-text index ): Full text index is also MyISAM A special type of , Mainly used for full-text indexing ,InnoDB Engine from MySQL5.6 Version starting support .
MySQL Four indexes are provided
| Index structure | InnoDB engine ( The main ) | MyISAM engine | Memory engine |
|---|---|---|---|
| BTREE Indexes | Support | Support | Support |
| HASH Indexes | Support | I won't support it | Support |
| R-tree Indexes | I won't support it | Support | I won't support it |
| Full-text | 5.6 Support for | Support | I won't support it |
So we often say index , If not specified , Basically refers to B+ Trees ( Multi index tree , It's not necessarily a binary structure ) Index of structural organization . among , Clustered index 、 Composite index 、 Prefix index 、 The only index defaults to B+tree Indexes , Collectively referred to as index .
BTREE structure ( a key )
BTree Also called multiplex Balance Search tree , A tree m fork Of BTree Characteristics are as follows :
- Every node in the tree Include at most m A child .
- Except root node and leaf node , Each node contains at least ==
ceil(m/2)== A child . - if The root node is not a leaf node , There are at least two children .
- All leaf nodes are on the same layer .
- Every Nonleaf node from n individual key And n+1 A pointer to the form , among ==
ceil(m/2) - 1 <= n <=m-1==, The so-called pointer field , In the following example, the second line of each path is blank . - The pointer represents which way to go .
With 5 Forked BTree For example ,key The number of : Formula derivation ceil(m/2) - 1 <= n <= m-1. therefore 2 <= n <= 4. When n > 4 when , The intermediate node splits into the parent node , The nodes on both sides split .
Insert with C N G A H E K Q M F W L T Z D P R X Y S Data as an example :
The evolution process is as follows :
1). Before insertion 4 Letters C N G A , Press ASSIC Code size sort ,2 <= n <= 4
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-ILTxpyGT-1644828555729)(2021-11-26-MySQL Index in .assets/image-20211126130804700.png)]](/img/50/93687b52b5eca68976b1c307be648e.png)
2). Insert H,n > 4, Trigger split threshold , The middle element G Letter Split up To a new node

3). Insert E K Q There is no need to split , Because it's all in n Within the scope of

4). Insert M, middle Elements M The letter splits up to the parent node G, Here we can see why every pointer should have n + 1 There are three reasons

5). Insert F W L T There is no need to split

6). Insert Z, The middle element T Split up into parent nodes

7). Insert D, The middle element D Split up into parent nodes . Then insert P,R,X,Y There is no need to split , Note that every time you insert one, you have to judge whether it is split

8). Finally insert S,N P Q R Node of this route n > 5, Intermediate nodes Q Split up , but Split parent node D G M T Of n > 5, Intermediate nodes M Split up
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-YCkDjHLT-1644828555731)(2021-11-26-MySQL Index in .assets/image-20211126130908282.png)]](/img/fe/6e38acb3f958bd62b0ecab4060f460.jpg)
Here we are , The BTREE The tree has been built , We can see that , Due to the number of layers ,BTREE Trees and Binary tree comparison , Query data more efficiently , Because for the same amount of data ,BTREE The hierarchical structure of a tree is smaller than that of a binary tree , So search speed is fast .
B+TREE
B+Tree by BTree Variants ,B+Tree And BTree The difference between :
- m fork Of B+Tree Up to m individual key, and BTree Up to m-1 individual key.
- B+Tree Of Leaf node preservation be-all key Information , Press key In order of size .
- be-all Non leaf nodes can be regarded as key The index part of .

because B+Tree Only Leaf node save key Information , Query any key All from root Go to the leaves . therefore B+Tree So == Query efficiency is more stable ==.
MySQL Medium B+Tree
MySQL Medium Index data structure For the classic B+Tree optimized . On the original basis , Added a linked list pointer to adjacent leaf nodes , Formed with sequence B+Tree , The advantage of this is to improve the new capability of interval access .
MySQL Medium B+Tree Index structure diagram ::

How to improve , We can take what we want lookup 17, Due to the existence of a pointer , We can quickly locate the interval , Directly from 15 node Just start looking , It greatly reduces the time complexity of positioning .
Classification of indexes ( important )
- Single value index : One The index contains only a single column , One A table can have multiple single column indexes , A list of regular suggestions Up to five single valued indexes , The index value can appear more than once .
- unique index : The value of the index column must be unique , However, it is allowed to be empty .
- Composite index : An index contains multiple columns .
Syntax of index ( important )
Indexes can be created simultaneously with tables , It can also be added at any time , stay MySQL Primary key field in , The primary key index is automatically created .
There are There are four ways to create : unique index , primary key , Single value index , There are four full-text indexes .
Prepare the environment
CREATE TABLE `city` (
`city_id` int(11) NOT NULL AUTO_INCREMENT,
`city_name` varchar(50) NOT NULL,
`country_id` int(11) NOT NULL,
PRIMARY KEY (`city_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `country` (
`country_id` int(11) NOT NULL AUTO_INCREMENT,
`country_name` varchar(100) NOT NULL,
PRIMARY KEY (`country_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `city` (`city_id`, `city_name`, `country_id`) values(1,' Xi'an ',1);
insert into `city` (`city_id`, `city_name`, `country_id`) values(2,' New York ',2);
insert into `city` (`city_id`, `city_name`, `country_id`) values(3,' Beijing ',1);
insert into `city` (`city_id`, `city_name`, `country_id`) values(4,' Shanghai ',1);
insert into `city` (`city_id`, `city_name`, `country_id`) values(5,' London ',4);
insert into `city` (`city_id`, `city_name`, `country_id`) values(6,' Tokyo ',3);
insert into `city` (`city_id`, `city_name`, `country_id`) values(7,' Osaka ',3);
insert into `city` (`city_id`, `city_name`, `country_id`) values(8,' Washington ',2);
insert into `country` (`country_id`, `country_name`) values(1,' China ');
insert into `country` (`country_id`, `country_name`) values(2,' The United States ');
insert into `country` (`country_id`, `country_name`) values(3,' Japan ');
insert into `country` (`country_id`, `country_name`) values(4,' The British ');
Create index
grammar :
CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name
[USING index_type] -- Select index classification , Do not specify default use B+Tree type
ON tbl_name(index_col_name, ...) -- Which field of which table , Two or more are indexes
index_col_name : column_name[(length)][ASC | DESC]
stay city Used in the table city_name Create a General index :
CREATE INDEX `index_city_name `
ON city(city_name);
Look at the index
grammar :
SHOW INDEX FROM tbl_name;
see city The index held by the table :
Here we will print out Index just created as well as primary key There are two indexes .
SHOW INDEX FROM `city`;
Delete index
grammar :
DROP INDEX index_name ON tbl_name;
We delete the created index_city_name Indexes :
DROP INDEX `index_city_name` ON `city`;
ALTER command
use ALTER To create or modify an index .
grammar :
-- Add a primary key , This means that the value of the index must be unique , And can't be empty
ALTER TABLE tbl_name ADD PRIMARY KEY(column_list);
-- The value to create the index must be unique ( For example, the name of a country cannot be repeated ), Can be null
ALTER TABLE tbl_name ADD UNIQUE index_name(column_list);
-- Create a normal index , Values can appear more than once
ALTER TABLE tbl_name ADD INDEX index_name(column_list);
-- Create full text index
ALTER TABLE tbl_name ADD FULLTEXT index_name(column_list);
The design principle of index ( important )
- Selection of index fields , The best candidate column should be where Clause in Common conditions , If where Clause There are many combinations of conditions in , You should choose the combination that is most commonly used and has the best filtering effect .
- Use unique index , The more distinguishable , The more efficient the index is .
- The number of indexes is not the more the better , More indexes , The higher the cost of maintenance :
- about Add, delete, change, etc DML ** Frequent operation For example , Too many indexes Will increase maintenance costs **, thus Reduce addition, deletion, modification, etc DML Efficiency of operation .
- about MySQL Come on , It's not the more the better , If you have too many indexes, you have to choose , The selection process also takes time .
- Use Short index , After the index is established, the following is Use a hard disk to store Of :
- Promote index access I/O operation efficiency , It's fine too Improve overall access efficiency .
- If The total length of the fields that make up the index is short Words , stay More indexes can be stored in a storage block of a given size , You can improve MySQL Access to the index I/O Efficiency of operation .
- utilize Left most prefix ,N A composite index of columns , So it's equivalent to creating N An index , If you query where Clause Used in The first few fields that make up the index , So this one Inquire about SQL We can use composite index to improve query efficiency .
- for example :
CREATE INDEX index_person_name_tel_email
ON person(person_name, person_tel, person_email);
-- It's equivalent to person_name Created index
-- Also at the same time person_name, person_tel Created index
-- That's right person_name, person_tel, person_email All the elements in the Cartesian product of are indexed
When it is recommended to build an index
- Primary key automatically creates unique index .
- Yes Query frequency is high , And the amount of data is large Table of Index .
- Query with other tables Correlation field , Index foreign key relationship .
- WHERE Conditions in Do not create an index for unused fields .
- Single value index / The choice of Composite Index :
- High and low , It is recommended to select composite index .
- Most frequent queries , The most frequently sorted fields :
- Fields sorted in the query , If the sorting field is accessed by index, the sorting speed will be greatly improved .
- Querying , Statistics or grouping fields , Grouping presupposes sorting .
When indexing is not recommended
- When tables record very little data .
- MySQL After 3million data, the retrieval efficiency will decrease without index .
- Frequently updated fields Not suitable for indexing , Improve query speed , Reduce update speed .
- Duplicate data , And evenly distributed table fields , Too much repetition , The lower the indexing effect .
JOIN Inquire about
Common queries
Take a systematic look at the fourth reason above join Inquire about .
To relive DQL The grammar of :
# artificial
SELECT DISTINCT
<select_list>
FROM
<left_table> <join_type>
JOIN <right_table> ON <join_condition>
WHERE
<where_condition>
GROUP BY
<group_by_list>
HAVING
<having_condition>
ORDER BY
<order_by_condition>
LIMIT <limit_number>
# Machine reading
FROM <left_table>
ON <join_condition>
<join_type> JOIN <right_table>
WHERE <where_condition>
GROUP BY <group_by_list>
HAVING <having_condition>
SELECT
DISTINCT <select_list>
ORDER BY <order_by_condition>
LIMIT <limit_number>
| 
| Machine readable sequence |
seven JOIN Inquire about
|
| seven JOIN Inquire about (Oracle) |
Test cases
CREATE TABLE t_dept(
id INT(11) NOT NULL AUTO_INCREMENT,
deptName VARCHAR(30) DEFAULT NULL,
locAdd VARCHAR(40) DEFAULT NULL,
PRIMARY KEY(id)
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE t_emp (
id INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) DEFAULT NULL,
deptId INT(11) DEFAULT NULL,
PRIMARY KEY (id),
KEY fk_dept_Id (deptId)
#CONSTRAINT 'fk_dept_Id' foreign key ('deptId') references 'tbl_dept'('Id')
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
INSERT INTO t_dept(deptName,locAdd) VALUES('RD',11);
INSERT INTO t_dept(deptName,locAdd) VALUES('HR',12);
INSERT INTO t_dept(deptName,locAdd) VALUES('MK',13);
INSERT INTO t_dept(deptName,locAdd) VALUES('MIS',14);
INSERT INTO t_dept(deptName,locAdd) VALUES('FD',15);
INSERT INTO t_emp(NAME,deptId) VALUES('z3',1);
INSERT INTO t_emp(NAME,deptId) VALUES('z4',1);
INSERT INTO t_emp(NAME,deptId) VALUES('z5',1);
INSERT INTO t_emp(NAME,deptId) VALUES('w5',2);
INSERT INTO t_emp(NAME,deptId) VALUES('w6',2);
INSERT INTO l_emp(NAME,deptId) VALUES('s7',3);
INSERT INTO t_emp(NAME,deptId) VALUES('s8',4);
INSERT INTO t_emp(NAME,deptId) VALUES('s9',51);
+----+----------+--------+
| id | deptName | locAdd |
+----+----------+--------+
| 1 | RD | 11 |
| 2 | HR | 12 |
| 3 | MK | 13 |
| 4 | MIS | 14 |
| 5 | FD | 15 |
+----+----------+--------+
5 rows in set (0.00 sec)
+----+------+--------+
| id | NAME | deptId |
+----+------+--------+
| 1 | z3 | 1 |
| 2 | z4 | 1 |
| 3 | z5 | 1 |
| 4 | w5 | 2 |
| 5 | w6 | 2 |
| 6 | s8 | 4 |
| 7 | s9 | 51 |
+----+------+--------+
7 rows in set (0.00 sec)
join Type 1 :

join Type 2 :
- The query results include All entries in the left table , Contains the intersection of two tables .
- Unique part of left table , In the table on the right, it shows , No supplement null.

join Type 3 :
- The query results include All entries in the right table , Include the cross section of the scale .
- The unique part of the right table , In the table on the left, it shows , There is no null.

join Type four :
- The results are The unique contents of the left table , The row in the right table is empty .

join Type five :
- The results are The contents unique to the right table , Left table row is empty .

- The results are The contents unique to the right table , Left table row is empty .
join Type 6 :
- The query result is all-round , The left and right tables are public 、 Private parts have .
- Syntax in the figure ,MySQL Of SQL Does not support , Only use UNION To jointly realize .

- join Type seven :
- The left table is the private part of the right table .

- The left table is the private part of the right table .
Code cloud warehouse synchronization notes , You can take it yourself. Welcome star correct :https://gitee.com/noblegasesgoo/notes
If something goes wrong, I hope the leaders in the comment area can discuss and correct each other , Maintain the health of the community. Let's work together , There is no tolerance for wrong knowledge .
—————————————————————— Love you noblegasesgoo
边栏推荐
- Post office - post office issues (dynamic planning)
- K-line diagram interpretation and practical application skills (see position entry)
- [binary tree] preorder traversal to construct binary search tree
- Development details of NFT casting trading platform
- [machine learning] K-means clustering analysis
- Map collection
- Communication network electronic billing system based on SSH
- uni-app进阶之内嵌应用【day14】
- 【剑指Offer】53 - I. 在排序数组中查找数字 I
- 大文件处理(上传,下载)思考
猜你喜欢

Redis (VII) - sentry

TCP session hijacking based on hunt1.5

Six photos vous montrent pourquoi TCP serre la main trois fois?

Develop those things: how to add text watermarks to videos?

News management system based on SSM
![leetcode:787. The cheapest transfer flight in station K [k-step shortest path + DFS memory + defaultdict (dict)]](/img/28/78e2961877776ca3dfcba5ee7e35d2.png)
leetcode:787. The cheapest transfer flight in station K [k-step shortest path + DFS memory + defaultdict (dict)]

Oneortwo bugs in "software testing" are small things, but security vulnerabilities are big things. We must pay attention to them

基于SSH的客户关系CRM管理系统

Share 5 commonly used feature selection methods, and you must see them when you get started with machine learning!!!

Only black-and-white box test is required for test opening post? No, but also learn performance test
随机推荐
Send the injured baby for emergency medical treatment. Didi's driver ran five red lights in a row
[zero basic IOT pwn] environment construction
Three methods of modifying time zone in MySQL
生成对抗网络,从DCGAN到StyleGAN、pixel2pixel,人脸生成和图像翻译。
DeFi借贷协议机制对比:Euler、Compound、Aave和Rari Capital
VS code 树视图 treeView
K-line diagram interpretation and practical application skills (see position entry)
Servlet operation principle_ API details_ Advanced path of request response construction (servlet_2)
Animesr: learnable degradation operator and new real world animation VSR dataset
Solution: STM32 failed to parse data using cjson
Development: how to install offline MySQL in Linux system?
Redis (II) -- persistence
Ten thousand volumes - list sorting [01]
Deep understanding of JVM (IV) - garbage collection (I)
Taishan Office Technology Lecture: how to align and draw words of different sizes on the same line
Redis (III) - transaction
Conception d'un centre commercial en ligne basé sur SSH
腾讯云安装mysql数据库
[sword finger offer] 53 - I. find the number I in the sorted array
同济、阿里的CVPR 2022最佳学生论文奖研究了什么?这是一作的解读