且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我什么时候应该使用复合索引?

更新时间:2022-12-08 12:23:47

当您使用从中受益的查询时,您应该使用复合索引。一个如下所示的复合索引:

You should use a composite index when you are using queries that benefit from it. A composite index that looks like this:

index( column_A, column_B, column_C )

将使用这些字段进行加入,过滤和有时选择的查询受益。它还将使在该组合中使用最左侧列的子集的查询受益。所以上面的索引也将满足需要的查询

will benefit a query that uses those fields for joining, filtering, and sometimes selecting. It will also benefit queries that use left-most subsets of columns in that composite. So the above index will also satisfy queries that need

index( column_A, column_B, column_C )
index( column_A, column_B )
index( column_A )

但它不会(至少不是直接的,也许是它可以部分帮助,如果没有更好的索引)帮助查询需要

But it will not (at least not directly, maybe it can help partially if there are no better indices) help for queries that need

index( column_A, column_C )

注意column_B是如何丢失的。

Notice how column_B is missing.

在原始示例中,两个维度的复合索引将主要有益于查询两个维度或最左边的维度本身,而不是最右边的维度本身。如果你总是在查询两个维度,那么复合索引是可行的方法,首先(最有可能)并不重要。

In your original example, a composite index for two dimensions will mostly benefit queries that query on both dimensions or the leftmost dimension by itself, but not the rightmost dimension by itself. If you're always querying two dimensions, a composite index is the way to go, doesn't really matter which is first (most probably).