作者:杨奇龙
网名“北在南方”,目前任职于杭州有赞科技 DBA,主要负责数据库架构设计和运维平台开发工作,擅长数据库性能调优、故障诊断。
本文来源:原创投稿
*爱可生开源社区出品,原创内容未经授权不得随意使用,转载请联系小编并注明来源。
前言
select * from tab where a=1 and b=2;
复制
场景 1
场景 2
create table x(id int not null auto_increment primary key, a int ,b int,key idx(a,b));
insert into x(a,b) values(1,8),(1,6),(1,3),(2,1),(2,2),(2,4),(3,7),(3,9);
复制
mysql> select * from x order by a, b;
+----+------+------+
| id | a | b |
+----+------+------+
| 3 | 1 | 3 |
| 2 | 1 | 6 |
| 1 | 1 | 8 |
| 4 | 2 | 1 |
| 5 | 2 | 2 |
| 6 | 2 | 4 |
| 7 | 3 | 7 |
| 8 | 3 | 9 |
+----+------+------+
8 rows in set (0.00 sec)
复制
mysql> select * from x where a=2 order by b;
+----+------+------+
| id | a | b |
+----+------+------+
| 4 | 2 | 1 |
| 5 | 2 | 2 |
| 6 | 2 | 4 |
+----+------+------+
3 rows in set (0.00 sec)
mysql> desc select * from x where a=2 order by b \G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: x
partitions: NULL
type: ref
possible_keys: idx
key: idx
key_len: 5
ref: const
rows: 3
filtered: 100.00
Extra: Using index
1 row in set, 1 warning (0.00 sec)
复制
mysql> select * from x where a>=1 and a<3 order by b;
+----+------+------+
| id | a | b |
+----+------+------+
| 4 | 2 | 1 |
| 5 | 2 | 2 |
| 3 | 1 | 3 |
| 6 | 2 | 4 |
| 2 | 1 | 6 |
| 1 | 1 | 8 |
+----+------+------+
6 rows in set (0.00 sec)
mysql> desc select * from x where a>=1 and a<3 order by b \G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: x
partitions: NULL
type: range
possible_keys: idx
key: idx
key_len: 5
ref: NULL
rows: 6
filtered: 100.00
Extra: Using where; Using index; Using filesort
1 row in set, 1 warning (0.01 sec)
复制
本文总结两种出现频率比较高的场景。希望开发同学看完本文之后,能设计出更合理的索引。
社区近期动态


最后修改时间:2021-03-18 22:12:53
文章转载自爱可生开源社区,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。
评论
相关阅读
2025年4月中国数据库流行度排行榜:OB高分复登顶,崖山稳驭撼十强
墨天轮编辑部
1971次阅读
2025-04-09 15:33:27
2025年3月国产数据库大事记
墨天轮编辑部
895次阅读
2025-04-03 15:21:16
2025年3月国产数据库中标情况一览:TDSQL大单622万、GaussDB大单581万……
通讯员
616次阅读
2025-04-10 15:35:48
征文大赛 |「码」上数据库—— KWDB 2025 创作者计划启动
KaiwuDB
508次阅读
2025-04-01 20:42:12
数据库,没有关税却有壁垒
多明戈教你玩狼人杀
497次阅读
2025-04-11 09:38:42
国产数据库需要扩大场景覆盖面才能在竞争中更有优势
白鳝的洞穴
477次阅读
2025-04-14 09:40:20
数据库国产化替代深化:DBA的机遇与挑战
代晓磊
463次阅读
2025-04-27 16:53:22
最近我为什么不写评论国产数据库的文章了
白鳝的洞穴
424次阅读
2025-04-07 09:44:54
【活动】分享你的压箱底干货文档,三篇解锁进阶奖励!
墨天轮编辑部
375次阅读
2025-04-17 17:02:24
天津市政府数据库框采结果公布,7家数据库产品入选!
通讯员
368次阅读
2025-04-10 12:32:35