【问题标题】:Does PostgreSQL implement multi-table indexes?PostgreSQL 是否实现了多表索引?
【发布时间】:2020-11-28 02:25:07
【问题描述】:

我已经搜索了一个星期了,恐怕这可能不存在 [还]。我想在 PostgreSQL 中使用跨越多个表的索引。 Oracle 和 SQL Server 似乎实现了它们(或多或少的选项)。

这对于我需要实现的一些搜索可能非常有用。

作为参考,以下是 Oracle 和 SQL Server 的多表索引示例:

Oracle 示例

Oracle可以创建位图连接索引,如下图:

create table dealer (
  id int primary key not null,
  city varchar2(20) not null
);

create table car (
  id int primary key not null,
  brand varchar2(20),
  price int,
  dealer_id int references dealer (id)
);

create bitmap index bix1 on car (d.city, c.brand)
from car c, dealer d
where d.id = c.dealer_id;

select avg(c.price)
from dealer d
join car c on c.dealer_id = d.id
where d.city = 'Chicago' and c.brand = 'Buick';

SQL Server 示例

SQL Server 可以创建索引视图

create table dealer (
  id int primary key not null,
  city varchar(20) not null
);

create table car (
  id int primary key not null,
  brand varchar(20),
  price int,
  dealer_id int references dealer (id)
);

create view v with schemabinding as
select d.city, c.brand, c.price, c.dealer_id
from dbo.dealer d
join dbo.car c on c.dealer_id = d.id;

create unique clustered index uix1 on v (city, brand, price);

select avg(c.price)
from dealer d
join car c on c.dealer_id = d.id
where d.city = 'Chicago' and c.brand = 'Buick';

【问题讨论】:

标签: sql postgresql indexing query-performance multi-table


【解决方案1】:

从 PostgreSQL (v 12) 的当前版本开始,索引只能基于表或物化视图。

https://www.postgresql.org/docs/current/sql-createindex.html

CREATE INDEX 在指定列上构造索引 指定关系,可以是表格,也可以是物化视图。

CREATE INDEX 语法需要一个表,并且只能指定一个表

创建[唯一]索引[并发][[如果不存在]名称]开启 [仅]表名[使用方法]

表名:
要索引的表的名称(可能是模式限定的)。

物化视图是一个选项,但在您刷新数据之前,物化视图中的数据是陈旧的。

https://www.postgresql.org/docs/12/sql-creatematerializedview.html

CREATE MATERIALIZED VIEW 定义查询的具体化视图。这 查询被执行并用于填充视图 发出命令(除非使用 WITH NO DATA)并且可以刷新 稍后使用 REFRESH MATERIALIZED VIEW。

您也许可以通过自动运行REFRESH MATERIALIZED VIEW 命令的流程来平衡它,以减少陈旧数据的可能性。例如,在导入大量数据之后以及在其他时间定期进行。但是,如果您的数据大到需要索引,那么刷新和重新索引过程将不够快,因此您将无法在 OLTP 场景中的每个 CRUD 语句之后执行它。

总之,从 v 12 起,PostgreSQL 中不存在您要查找的内容。

【讨论】:

  • 谢谢,我认为这个选项可以解决某些情况。然而,数据的陈旧性质限制了可以应用的场景范围。
  • 我同意。物化视图不是您希望在 OLTP 场景中拥有的东西,除非您真的必须这样做,因为在某些时候很难避免数据过时。但是,它在 CRUD 由 ETL 控制的 OLAP 场景中可能很有用,因此您知道何时准确刷新数据。但即便如此,如果您有大量数据并且有能力这样做,您更愿意将增量数据加载到常规表中,而不是在物化视图上进行完全刷新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-21
  • 1970-01-01
相关资源
最近更新 更多