当一个表的数据量较大时,我们需要对这个表做优化,除了分表分库以外,最常见的就是索引优化了,那做索引优化的原则是什么呢?
在不考虑排序,分组时,也就是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)