我已经找了一个星期了,恐怕这可能不存在[还]。我想在 PostgreSQL 中使用一个跨越多个表的索引。 Oracle 和 SQL 服务器似乎实现了它们(或多或少的选项)。
对于我需要实现的某些搜索,它可能非常有用。
作为引用,这里是 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 可以创建索引 View :
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';
最佳答案
从 PostgreSQL (v 12) 的当前版本开始,索引只能基于表或物化 View 。
https://www.postgresql.org/docs/current/sql-createindex.html
CREATE INDEX constructs an index on the specified column(s) of the specified relation, which can be a table or a materialized view.
CREATE INDEX
语法需要一个表,并且只能指定 1 个表CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ [ IF NOT EXISTS ] name ] ON [ ONLY ] table_name [ USING method ]
table_name:
The name (possibly schema-qualified) of the table to be indexed.
物化 View 是一个选项,但物化 View 中的数据在您刷新数据之前都是陈旧的。
https://www.postgresql.org/docs/12/sql-creatematerializedview.html
CREATE MATERIALIZED VIEW defines a materialized view of a query. The query is executed and used to populate the view at the time the command is issued (unless WITH NO DATA is used) and may be refreshed later using REFRESH MATERIALIZED VIEW.
您也许可以通过自动化流程来平衡它
REFRESH MATERIALIZED VIEW
命令以减少陈旧数据的可能性。例如,在大数据导入之后和其他时间的固定间隔。但是,如果您的数据大到需要索引,刷新和重新索引过程将不够快,因此您将无法在 OLTP 场景中的每个 CRUD 语句之后执行它。总之,从 v 12 开始,PostgreSQL 中不存在您要查找的内容。
关于sql - PostgreSQL 是否实现了多表索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63307039/