針對多列索引,如何確定哪一列位於第一列?這就要用到我前面提到的索引的選擇性。通常根據經驗法則:將選擇性最高的列放到索引最前列。
由此引入了一個問題,計算選擇性。舉個栗子:
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的選擇性更高,因此應將其放到第一列。