MySQL索引最左匹配原則


原創轉載請注明出處:https://www.cnblogs.com/agilestyle/p/11609103.html

 

創建一個測試表

 1 CREATE TABLE `test` (
 2   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 3   `a` varchar(32) NOT NULL,
 4   `b` varchar(32) NOT NULL,
 5   `c` varchar(64) NOT NULL,
 6   `d` varchar(128) NOT NULL,
 7   `e` varchar(256) NOT NULL,
 8   `create_time` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),  
 9   `update_time` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3), 
10   PRIMARY KEY (`id`)
11 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

 

插入數據

 1 INSERT INTO `test` (`a`, `b`, `c`, `d`, `e`) VALUES('a', 'b', 'c', 'd', 'e');
 2 INSERT INTO `test` (`a`, `b`, `c`, `d`, `e`) VALUES('a', 'b', 'c', 'd', 'e');
 3 INSERT INTO `test` (`a`, `b`, `c`, `d`, `e`) VALUES('a', 'b', 'c', 'd', 'e');
 4 INSERT INTO `test` (`a`, `b`, `c`, `d`, `e`) VALUES('a', 'b', 'c', 'd', 'e');
 5 INSERT INTO `test` (`a`, `b`, `c`, `d`, `e`) VALUES('a', 'b', 'c', 'd', 'e');
 6 INSERT INTO `test` (`a`, `b`, `c`, `d`, `e`) VALUES('a', 'b', 'c', 'd', 'e');
 7 INSERT INTO `test` (`a`, `b`, `c`, `d`, `e`) VALUES('a', 'b', 'c', 'd', 'e');
 8 INSERT INTO `test` (`a`, `b`, `c`, `d`, `e`) VALUES('a', 'b', 'c', 'd', 'e');
 9 INSERT INTO `test` (`a`, `b`, `c`, `d`, `e`) VALUES('a', 'b', 'c', 'd', 'e');
10 INSERT INTO `test` (`a`, `b`, `c`, `d`, `e`) VALUES('a', 'b', 'c', 'd', 'e');

 

查看索引

1 show index from test;

 

查看執行計划

1 explain select * from test where id = "1";

 

1 explain select * from test where a = "1";

 

1 explain select * from test where b = "1";

 

1 explain select * from test where a = "1" and b = "1";

 

創建索引(a和b的聯合索引)

1 create index idx_a_b on test(a, b);

 

查看索引

1 show index from test;

 

查看執行計划

1 explain select * from test where a = "1";

 

1 explain select * from test where b = "1";

 

1 explain select * from test where a = "1" and b = "1";

 

創建索引(b的索引)

1 create index idx_b on test(b);

 

查看索引

1 show index from test;

 

查看執行計划

1 explain select * from test where a = "1";

 

1 explain select * from test where b = "1";

 

1 explain select * from test where a = "1" and b = "1";

 

刪除索引

1 drop index idx_a_b on test;
2 drop index idx_b on test;

 

刪除索引后,創建a, b, c 3個字段的聯合索引

1 create index idx_a_b_c on test(a, b, c);

 

查看如下語句的執行計划

 1 -- ref
 2 explain select * from test where a = "1";
 3 -- all 掃全表
 4 explain select * from test where b = "1";
 5 -- all 掃全表
 6 explain select * from test where c = "1";
 7 -- ref
 8 explain select * from test where a = "1" and b = "1" and c = "1";
 9 -- ref
10 explain select * from test where a = "1" and b = "1";
11 -- ref
12 explain select * from test where a = "1" and c = "1"
13 -- all 掃全表
14 explain select * from test where b = "1" and c = "1"



  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM