为 postgres 数据库字段创建复合索引

问题描述 投票:0回答:1

我在 postgresql 数据库中有下表

ID | first_name | last_name    | class      | position |
--------------------------------------------------------
 1 | Teemo      | Shroomer     | Specialist | Top      |
 2 | Cecil      | Heimerdinger | Specialist | Mid      |
 3 | Annie      | Hastur       | Mage       | Mid      |
 4 | Fiora      | Laurent      | Slayer     | Top      |
 5 | Garen      | Crownguard   | Fighter    | Top      |
 6 | Malcolm    | Graves       | Specialist | ADC      |
 7 | Irelia     | Lito         | Figher     | Top      |
 8 | Janna      | Windforce    | Controller | Support  | 

并且在 3 个不同的存储过程中有 3 个 WHERE 子句。

WHERE first_name = 'Annie'
WHERE first_name = 'Annie' AND class = 'Mage'
WHERE first_name = 'Janna' AND class = 'Controller' AND position = 'Support'

我为我的表创建了如下索引

CREATE INDEX first_name_index ON users (first_name);
CREATE INDEX first_name_class_index ON users (first_name, class);

我对创建的索引有几个问题。

  1. 因为我已经有了first_name + class的复合索引。我真的只需要名字字段的单个索引吗?如果我理解正确,那么仅使用first_name进行搜索可以受益于复合索引“first_name_class_index”

  2. 如果我使用第三个 WHERE 子句(具有 3 个字段),我使用“first_name_class_index”有什么好处吗?索引内部会首先使用复合索引(first_name + class)执行搜索,然后从获得的列表中搜索“位置”。正确吗?

database postgresql indexing composite-index
1个回答
0
投票

单列索引基本上没什么用,你应该放弃它。两列索引做不到的事情它都做不到;它唯一的好处是它更小,所以 PostgreSQL 在第一个查询中更喜欢它。

两列索引也将有助于第三个查询。当表中有足够的数据时,PostgreSQL通常会使用索引扫描并添加第三个条件作为过滤器。

© www.soinside.com 2019 - 2024. All rights reserved.