有一张表结构定义如下:
## 创建表
CREATE TABLE `hecg` (
`a` int(11) NOT NULL,
`b` int(11) NOT NULL,
`c` int(11) NOT NULL,
`d` int(11) NOT NULL,
PRIMARY KEY (`a`,`b`),
KEY `c` (`c`),
KEY `ca` (`c`,`a`),
KEY `cb` (`c`,`b`) ) ENGINE=InnoDB;
## 查询语句
select * from hecg where c=N order by a limit 1;
select * from hecg where c=N order by b limit 1;
## 初始化数据
mysql> select * from hecg;
--- --- --- ---
| a | b | c | d |
--- --- --- ---
| 1 | 2 | 3 | 0 |
| 1 | 3 | 2 | 0 |
| 1 | 4 | 3 | 0 |
| 2 | 1 | 3 | 0 |
| 2 | 2 | 2 | 0 |
| 2 | 3 | 4 | 0 |
--- --- --- ---
问题:主键包含了 a、b 这两个字段,在字段 c 上创建一个索引,就已经包含了三个字段了呀,为什么要创建ca和cb这两个索引?
主键 a,b 的聚簇索引组织顺序相当于 order by a,b ,也就是先按 a 排序,再按 b 排序, c 无序
-
索引 ca 的组织是先按 c 排序,再按 a 排序,同时记录主键
--- --- --- | c | a |主b| --- --- --- | 2 | 1 | 3 | | 2 | 2 | 2 | | 3 | 1 | 2 | | 3 | 1 | 4 | | 3 | 2 | 1 | | 4 | 2 | 3 | --- --- ---
注意主键部分,这里不是 ab,而是只有 b。这个跟索引 c 的数据是一模一样的。
-
索引 cb 的组织是先按 c 排序,在按 b 排序,同时记录主键
--- --- --- | c | b |主a| --- --- --- | 2 | 2 | 2 | | 2 | 3 | 1 | | 3 | 1 | 2 | | 3 | 2 | 1 | | 3 | 4 | 1 | | 4 | 3 | 2 | --- --- ---
得出修改结论:
ca 可以去掉,cb 需要保留