当前位置:网站首页>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
边栏推荐
猜你喜欢
misc ez_ usb
Ansible
2022茶艺师(初级)考试题模拟考试题库及在线模拟考试
[SUCTF 2019]Game
【webrtc】m98 screen和window采集
[Stanford Jiwang cs144 project] lab3: tcpsender
Cnopendata list data of Chinese colleges and Universities
Mysql高低版本切换需要修改的配置5-8(此处以aicode为例)
[ANSYS] learning experience of APDL finite element analysis
Codeforces Global Round 19
随机推荐
面试结束后,被面试官在朋友圈吐槽了......
[Stanford Jiwang cs144 project] lab3: tcpsender
2022茶艺师(初级)考试题模拟考试题库及在线模拟考试
Ansible
nacos
pytorch 参数初始化
Cnopendata American Golden Globe Award winning data
Common validation comments
Qt学习28 主窗口中的工具栏
快速使用 Jacoco 代码覆盖率统计
【webrtc】m98 screen和window采集
Zhilian + AV, AITO asked M7 to do more than ideal one
直播平台源码,可折叠式菜单栏
[2022 ciscn] replay of preliminary web topics
[CV] Wu Enda machine learning course notes | Chapter 8
KBU1510-ASEMI电源专用15A整流桥KBU1510
Codeforces Global Round 19
Visualization Document Feb 12 16:42
Button wizard script learning - about tmall grabbing red envelopes
[unity] several ideas about circular motion of objects