选择合适的索引列顺序

针对多列索引,如何确定哪一列位于第一列?这就要用到我前面提到的索引的选择性。通常根据经验法则:将选择性最高的列放到索引最前列。

由此引入了一个问题,计算选择性。举个栗子:

select * from payment where staff_id = 2 and customer_id = 268   那么是应该创建一个(staff_id, customer_id)索引,还是应该颠倒顺序呢?我们可以通过以下方法来进行计算和比较,然后得出结论。执行以下sql语句:

select count(DISTINCT staff_id)/count(*) as staff_id_selectivity,count(DISTINCT customer_id)/count(*),count(*)  from payment;  结果如下:

staff_id_selectivity:0.0001

customer_id_selectivity:0.0373

count(*):16049

customer_id的选择性更高,因此应将其放到第一列。

posted @ 2019-04-12 08:30  水滴月  阅读(1562)  评论(0编辑  收藏  举报