sql - PostgreSQL 是否实现了多表索引?

标签 sql postgresql indexing query-performance multi-table

我已经找了一个星期了,恐怕这可能不存在[还]。我想在 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/

相关文章:

mysql - 如何获取大表的计数?

python - Django 测试时未找到 Postgres 函数 json_array_elements

python - 从 Python 数组创建 NxM 索引

arrays - 根据在另一个矩阵中的排序对矩阵进行排序

sql - 我是否在数据库中错误地使用了正则表达式?

mysql - 只为每个员工和 MySQL 中的特定员工选择最新记录

sql - DBMS查询日志,可能吗?

postgresql - 如何在 docker 中恢复 postgres?

django: IntegrityError: 重复键值违反唯一约束

sql - MariaDB是否支持重命名索引?