【问题标题】:Speeding up Joins with Indexes使用索引加速连接
【发布时间】:2018-06-14 12:10:30
【问题描述】:

我了解使用索引有助于加快两个或多个表的连接速度。以下示例使用共享的 department_id 列连接两个表,emps 和 depts:

select last_name, department_name 
from emps join depts 
using(department_id);

我的问题是:在两个表之一上索引 department_id 列会加快查询速度,还是我必须在两个表中的两个 department_id 列上创建索引才能看到性能改进?

【问题讨论】:

  • 在其中一张表上建立索引将使查询受益。想必depts(department_id)是主键,所以已经有索引了。

标签: sql indexing


【解决方案1】:

这两个表自然会在department_id 上有一个索引,因为这应该是depts 主键和emps 外键。

不过,在您的查询中,不太可能使用索引。当最终要读取所有记录时,为什么 DBMS 还要费心扫描索引树?例如,简单的顺序全表扫描然后连接哈希通常会快得多。

让我们看另一个例子:

select e.last_name, d.department_name 
from emps e
join depts d on d.department_id  = e.department_id
where e.first_name = 'Laura';

在这里,我们只对少数员工感兴趣。这就是索引发挥作用的地方。我们需要emps(first_name) 的索引。然后我们会知道员工记录,department_id,我们可以访问关联的dept 记录。

但是说到这里,我们注意到我们使用索引来查找表记录来查找department_id。从索引中获取department_id 不是更快吗?是的。所以索引应该在emps(first_name, department_id)

depts的主键是department_id,所以这列被索引了,我们可以很容易地找到depts的记录与部门名称。

但是我们可以再次问同样的问题:我们不能也从索引中获得名称吗?这导致我们覆盖包含查询中使用的所有列的索引。

所以,虽然

index idx_emps on emps(first_name, department_id)
index idx_depts on depts(department_id)

足够了,我们可以使用这些覆盖索引更快地进行查询:

index idx_emps on emps(first_name, department_id, last_name)
index idx_depts on depts(department_id, department_name)

【讨论】:

    【解决方案2】:

    您应该始终索引 pk 和 fks 以减少阻塞和争用,同时 DB 强制执行一致性和完整性。

    我还建议明确加入,而不是 USING。那里有太多的约定和魔法:)

    【讨论】:

    • 什么样的“魔法”?它完全可读且无样板。
    猜你喜欢
    • 1970-01-01
    • 2020-02-20
    • 2018-02-03
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 2015-08-31
    • 1970-01-01
    相关资源
    最近更新 更多