当前位置:网站首页>MySQL multi column index (composite index) features and usage scenarios
MySQL multi column index (composite index) features and usage scenarios
2022-07-07 07:53:00 【CaptainCats】
mysql Multi column index features and usage scenarios
Create a table first , Have a surname ’first_name’、 name ’last_name’、 Father ID Etc :
CREATE TABLE `users` (
`id` int NOT NULL AUTO_INCREMENT COMMENT ' Primary key ID',
`user_id` int NOT NULL COMMENT ' user ID',
`first_name` varchar(32) DEFAULT NULL COMMENT ' surname ',
`last_name` varchar(32) DEFAULT NULL COMMENT ' name ',
`parent_id` int NOT NULL COMMENT 'parentID',
`created_by` varchar(32) NOT NULL DEFAULT 'sys' COMMENT ' The creator ',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ' Creation time ',
`updated_by` varchar(32) NOT NULL DEFAULT 'sys' COMMENT ' Reviser ',
`updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ' Modification time ',
`is_deleted` varchar(1) NOT NULL DEFAULT '0' COMMENT ' Whether or not to delete :0 Not delete 、1 deleted ',
PRIMARY KEY (`id`),
KEY `index_user_id` (`user_id`) USING BTREE,
KEY `index_first_name` (`first_name`) USING BTREE,
KEY `index_last_name` (`last_name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3 COMMENT=' User table ';
Next we add some data , Put the code behind .

Single index
We know ,
where Only one index can be used ,mysql Will look for the index that it thinks is the best , The most restrictive index ,
But for multiple single column indexes ,mysql5.0 And above will be indexed and merged , And merge the results .
see sql Implementation plan of
EXPLAIN SELECT * FROM `users` WHERE first_name = 'Vm5' AND last_name = 'utD';

You can see type yes index_merge, This is index merging .
Index merging
Index merging can be divided into three types :or union 、and The intersection 、and and or combination ,
Queries can use multiple single column indexes at the same time , And merge the results , It means extra consumption cpu、 Memory and other resources ,
Even so, it is cheaper than using only one index .
Index merging strategy is an optimization , If this happens, usually , It usually indicates that a multi column index containing related columns is needed .
Multi column index
Build an index on multiple fields according to the query requirements , To some extent, you can use the values of multiple columns to locate the specified row .
We added a that contains first_name、last_name Multi column index of index_first_last_name:
ALTER TABLE `users` ADD KEY `index_first_last_name` (`first_name`,`last_name`) USING BTREE;
Look again sql Implementation plan of
EXPLAIN SELECT * FROM `users` WHERE first_name = 'Vm5' AND last_name = 'utD';

Visible in WHERE first_name = ‘?’ AND last_name = '?' when ,
The multi column index limit is stronger than the previous single column index , Or more ,
mysql You can find a match immediately first_name then last_name.
But be careful :
SELECT * FROM `users` WHERE first_name = 'Vm5' OR last_name = 'utD';
here ’or’ You can't use multiple column indexes .
Compared with multiple single column indexes , Will take up less disk space .
If you are interested, you can have a look at
adopt B+Tree Balanced multitree understanding InnoDB Clustered and nonclustered indexes of the engine
Order of multi column indexes
The order of multi column indexes is crucial ,
Experience tells us , Place the column with high selectivity on the left ( But not absolutely ),
You need to consider the overall query requirements , Instead of a specific query .
image :
KEY index_first_last_name (first_name,last_name)
Sometimes we just need to know the user's last name ,
Sometimes you may count the number of people with a certain surname , So here first_name To the left .
SELECT * FROM `users` WHERE last_name = 'utD';
Only last_name As a filter , There is also no need for multi column indexes .
Left most prefix
about :
KEY a_b_c (a,b,c)
The leftmost column of a multi column index must appear in the filter criteria , And can't jump ,
Otherwise, the leftmost prefix will be invalid , Greatly reduce the query efficiency .
The scenarios where the leftmost prefix can be used are :a、a&b、a&b&c,
a&c、b&c This kind is unusable .
Script for adding data
I'm through main Function to print sql, Then the output console To the file , Save as script .
public static void main(String[] args) {
System.out.println("INSERT INTO `users` (`user_id`, `first_name`, `last_name`, `parent_id`) VALUES");
for (int i = 1; i < 130001; i++) {
StringBuilder sqlSb = new StringBuilder();
sqlSb.append("(");
sqlSb.append(i + ", ");
sqlSb.append("'" + RandomStringUtils.randomAlphanumeric(3) + "', ");
sqlSb.append("'" + RandomStringUtils.randomAlphanumeric(3) + "', ");
sqlSb.append(i/1000);
sqlSb.append(")");
if (i < 130000) {
sqlSb.append(",");
} else {
sqlSb.append(";");
}
System.out.println(sqlSb.toString());
}
}
Right click class →run configurations→common

Reference article :
Guo Er Ma :MySQL The selection efficiency of single column index and combined index is the same as explain analysis
Yuwen 100: Correct understanding Mysql Column index and multi column index
duanx:mysql Index five : Multi column index
边栏推荐
- 面试结束后,被面试官在朋友圈吐槽了......
- 242. Bipartite graph determination
- 【VHDL 并行语句执行】
- 今日现货白银操作建议
- Linux server development, MySQL stored procedures, functions and triggers
- Zhilian + AV, AITO asked M7 to do more than ideal one
- Pytest+allure+jenkins installation problem: pytest: error: unrecognized arguments: --alluredir
- Asemi rectifier bridge rs210 parameters, rs210 specifications, rs210 package
- 2022焊工(初级)判断题及在线模拟考试
- Cnopendata geographical distribution data of religious places in China
猜你喜欢
![[ANSYS] learning experience of APDL finite element analysis](/img/bc/dc0742c308816553a80d50d1a990e3.jpg)
[ANSYS] learning experience of APDL finite element analysis

科技云报道:从Robot到Cobot,人机共融正在开创一个时代

After the interview, the interviewer roast in the circle of friends

Jenkins remote build project timeout problem

Use and analysis of dot function in numpy

Kbu1510-asemi power supply special 15A rectifier bridge kbu1510
![[2022 CISCN]初赛 web题目复现](/img/1c/4297379fccde28f76ebe04d085c5a4.png)
[2022 CISCN]初赛 web题目复现

Qt学习28 主窗口中的工具栏

ASEMI整流桥RS210参数,RS210规格,RS210封装
![[guess-ctf2019] fake compressed packets](/img/a2/7da2a789eb49fa0df256ab565d5f0e.png)
[guess-ctf2019] fake compressed packets
随机推荐
leetcode:105. 从前序与中序遍历序列构造二叉树
Rust Versus Go(哪种是我的首选语言?)
Detailed explanation of Kalman filter for motion state estimation
Pytest + allure + Jenkins Environment - - achèvement du remplissage de la fosse
[Stanford Jiwang cs144 project] lab3: tcpsender
[performance pressure test] how to do a good job of performance pressure test?
[2022 CISCN]初赛 web题目复现
php导出百万数据
misc ez_usb
pytest+allure+jenkins環境--填坑完畢
[webrtc] m98 Screen and Window Collection
IO stream file
The configuration that needs to be modified when switching between high and low versions of MySQL 5-8 (take aicode as an example here)
What are the positions of communication equipment manufacturers?
Qt学习26 布局管理综合实例
Installing postgresql11 database under centos7
Jenkins remote build project timeout problem
图解GPT3的工作原理
Jenkins远程构建项目超时的问题
gslx680触摸屏驱动源码码分析(gslX680.c)