2017-08-01 59 views
0

只是为了更好地了解在哪些情况下索引正确使用我想列举可能的情况。我们假设我们有一个“a”,“b”,“c”,“d”列的表格。postgres:当使用索引

我们创建(A,B,C,d)的索引:

create index my_index on table my_table (a, b, c, d) 

是当用于

1)

where a=% and b=% and c=% and d=% 

2)

where a=% and b=% 

3)

where a=% 

4)

where b=% and c=% and d=% 

5)

where c=% order by b 

6)

where a=% and b=% and c=% order by case when d is not null then d else c end 

7) 假设现在我们有7个点,但该指数更列仅限于(a,b,c,d)

where a=% and b=% and c=% and d=% and e=% and f=% and g=% 

回答

3

MySQL有很好的解释多列索引的documentation。规则在数据库中基本相同(虽然有一些更高级的东西)。

当然,还有其他因素 - 例如from子句中发生了什么,正在选择哪些列,关于表的统计信息等等。

以下是基本的指导:

1)where a=% and b=% and c=% and d=%

是的,只要所有条件都平等。我不知道整理冲突会发生什么。

2)其中a =%和b =%

是,只要所有条件都平等。我不知道整理冲突会发生什么。

3)其中,a =%

是,只要所有条件都平等。我不知道整理冲突会发生什么。

4)其中b =%和c =%和d =%

可能不是。如果使用,则需要扫描索引。如果索引涵盖了查询,则会是这种情况。

5)其中c =由b排序的%

可能不是。

6)其中,a =%和b =%和c =%为了通过情况下,当d不为空则d,否则c结束

应用于where子句。仍然需要排序。

+1

它也取决于值的分布,如果只有2个可能的值,并且有成千上万或数百万记录,其中a =%可能不会导致索引的使用。 – aschoerk

+0

@aschoerk。 。 。好点子。我澄清了答案。 –

+0

对不起,我添加了一个7)案例编辑 – 91DarioDev