40.3. Materialized Views

Posted 丹心明月

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了40.3. Materialized Views相关的知识,希望对你有一定的参考价值。

40.3 物化视图

物化视图与视图类似,也适用规则系统,不过物化视图保留结果集。

CREATE MATERIALIZED VIEW mymatview AS SELECT * FROM mytab;

CREATE TABLE mymatview AS SELECT * FROM mytab;

之间,最主要的区别是物化视图不可直接被更新,需要刷新物化视图数据:

REFRESH MATERIALIZED VIEW mymatview;

假设有表:

CREATE TABLE invoice (
invoice_no integer PRIMARY KEY,
seller_no integer, -- ID of salesperson
invoice_date date, -- date of sale
invoice_amt numeric(13,2) -- amount of sale
);

如果需要查看数据汇总,但无需最新数据,则可创建物化视图:

CREATE MATERIALIZED VIEW sales_summary AS
SELECT
seller_no,
invoice_date,
sum(invoice_amt)::numeric(13,2) as sales_amt
FROM invoice
WHERE invoice_date < CURRENT_DATE
GROUP BY
seller_no,
invoice_date
ORDER BY
seller_no,
invoice_date;


CREATE UNIQUE INDEX sales_summary_seller
ON sales_summary (seller_no, invoice_date);

访问物化视图数据较表或视图更快,但需要定期刷新数据到物化视图中。

以上是关于40.3. Materialized Views的主要内容,如果未能解决你的问题,请参考以下文章

Materialized View模式

Postgresql - MATERIALIZED VIEW

Materialized View模式

Materialized View模式

权限不足When Creating a Materialized View Log

如何为 postgresql MATERIALIZED VIEW 创建 typeorm 实体