当一个表的数据量较大时,我们需要对这个表做优化,除了分表分库以外,最常见的就是索引优化了,那做索引优化的原则是什么呢?
在不考虑排序,分组时,也就是SQL语句中只有where的时候,多列并查如
select * from payment where staff_id=? and customer_id=?
的索引原则,谁的数量多,把谁作为最左索引,最左索引在MySQL的B+树结构里的位置是很重要的。
select count(distinct staff_id)/count(*) staff_id_selectivity,count(disctinct customer_id)/count(*) customer_id_selectivity,count(*) from payment\G
加入运行结果为 staff_id_selectivity:0.0001
customer_id_selectivity:0.0373
count(*):16049
很明显customer_id的占比大,结果为
alter table payment add key(customer_id,staff_id)
在数据库优化中,索引扮演着关键角色。对于含有大量数据的表,创建合适的索引可以显著提升查询效率。在不考虑排序和分组的SQL查询(如WHERE子句)中,多列索引的选择应遵循‘最左前缀’原则,即数量较多的列放在前面。例如,在`payment`表中,`customer_id`的分布比`staff_id`更广泛。通过计算selectivity,发现`customer_id`的区分度更高。因此,优化建议是创建一个以`customer_id`为主,`staff_id`为次的复合索引。执行`ALTER TABLE payment ADD KEY (customer_id, staff_id)`即可完成优化。

被折叠的 条评论
为什么被折叠?



