【问题标题】:postgres: when index is usedpostgres:使用索引时
【发布时间】:2017-08-01 12:28:21
【问题描述】:

为了更好地了解在哪些情况下正确使用了索引,我想列举可能的情况。

假设我们有一个包含“a”、“b”、“c”、“d”列的表。

我们在 (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=%

【问题讨论】:

    标签: sql postgresql indexing


    【解决方案1】:

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

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

    以下是基本指导:

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

    可以,只要所有条件都相等。我不知道排序规则冲突会发生什么。

    2) 其中 a=% 和 b=%

    可以,只要所有条件都相等。我不知道排序规则冲突会发生什么。

    3) 其中 a=%

    可以,只要所有条件都相等。我不知道排序规则冲突会发生什么。

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

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

    5) 其中 c=% order by b

    可能不会。

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

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

    【讨论】:

    • 这也取决于值的分布,如果 a 只有 2 个可能的值,并且有数千或数百万条记录,其中 a = % 可能不会导致索引的使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多