在一个多列索引(x,y,z)上查询列(x,z)。

8 浏览
0 Comments

在一个多列索引(x,y,z)上查询列(x,z)。

我有一个类似的表格:

CREATE TABLE t (
  x some_type_1,
  y some_type_2,
  z some_type_3,
  PRIMARY KEY (x, y, z)
);

现在我想要高效地执行这个查询:

SELECT * FROM t WHERE x = ? AND z = ?;

在这种情况下,(主键)索引(x, y, z)足够了吗?或者我应该创建一个单独的索引(x, z)

0
0 Comments

现有的主键索引应该足够满足这种情况,因为使用PRIMARY KEY (x, y, z)实际上就相当于有了一个覆盖索引。查看什么是覆盖索引?

However, if there is a specific need to query on columns (x, z) for a multi-column index (x, y, z), it is possible to create such an index to optimize the query performance.

然而,如果有特定的需要在多列索引(x, y, z)上查询列(x, z),可以创建这样的索引来优化查询性能。

To create a multi-column index, the following SQL statement can be used:

为了创建一个多列索引,可以使用以下SQL语句:

CREATE INDEX index_name ON table_name (x, y, z);

This statement creates an index called "index_name" on the table "table_name" with the columns (x, y, z) in that order.

这个语句在表"table_name"上创建一个索引"index_name",索引的列按照(x, y, z)的顺序排列。

Once the index is created, queries that involve the columns (x, z) will benefit from the index and the query performance will be improved.

索引创建完成后,涉及到列(x, z)的查询将受益于索引,查询性能将得到提高。

In summary, if there is a need to query on specific columns for a multi-column index, it is recommended to create a separate index on those columns to optimize the query performance.

0
0 Comments

查询在多列索引(x,y,z)上的列(x,z)的原因是索引的可优化性。尽管主键索引对于查询来说已经足够了,但它并不是最优的。

为了让Postgres使用索引,它需要扫描索引中的所有条目,其中x = ?,以找到与z匹配的值。这可能已经足够好的性能了。

但是,查询的最佳索引应该是(x,z,y),因为它覆盖了查询并有效地满足了where子句。次佳索引是(x,z),因为它覆盖了where子句。现有的主键索引将部分用于where子句(假设表的统计信息表明应使用索引)。

0