PostgreSQL 是否实现了多表索引?

The*_*ler 5 sql postgresql indexing query-performance multi-table

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

对于我需要实现的某些搜索,它可能非常有用。

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

甲骨文示例

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';
Run Code Online (Sandbox Code Playgroud)

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';
Run Code Online (Sandbox Code Playgroud)

K4M*_*K4M 8

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

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

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

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

CREATE [唯一]索引[同时][[如果不存在]名称]ON[仅]表名[使用方法]

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

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

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

CREATE MATERIALIZED VIEW 定义查询的物化视图。该查询在发出命令时执行并用于填充视图(除非使用了WITH NO DATA),并且可以稍后使用 REFRESH MATERIALIZED VIEW 进行刷新。

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

总之,自版本 12 起,您正在寻找的内容在 PostgreSQL 中并不存在。