PostgreSQL Tutorial: Materialized Views

As mentioned earlier, a normal view is essentially a SQL statement. A normal view does not store any physical data on the local disk.

This SQL is executed every time the view is queried. There is a problem with efficiency.

As you can tell from the name, materialized views must persist a copy of data. The usage routines and views are basically the same. In this way, querying the materialized view is equivalent to querying a separate table. Compared with the previous ordinary views, materialized views do not need to query complex SQL every time. Each query is a piece of data (table) in the real physical storage address.

Because materialized views are persisted locally, they are completely separated from the original table structure.

Moreover, the materialized view can set index and other information separately to improve the query efficiency of the materialized view.

But, there are advantages and disadvantages, and the update time is not easy to control. If the updates are frequent, the pressure on the database will not be small. If updates are infrequent, data will be delayed and the real-time performance will be poor.

If you want to update the materialized view, you can use a trigger. When the data in the original table is written, you can use the trigger to perform the synchronization of the materialized view. Or complete data synchronization of materialized views based on scheduled tasks.

Look at the syntax.

image.png

Work!

-- 构建物化视图
create materialized view mv_test as (select id,name,price from test);
-- 操作物化视图和操作表的方式没啥区别。
select * from mv_test;
-- 操作原表时,对物化视图没任何影响
insert into test values (4,'月饼',50,10);
-- 物化视图的添加操作(不允许写物化视图),会报错
insert into mv_test values (5,'大阅兵',66);

How materialized views perform synchronization operations from the original table.

PostgreSQL provides two methods for synchronizing materialized views, one is full update and the other is incremental update.

Full syntax update, no restrictions, direct execution, full update

-- 查询原来物化视图的数据
select * from mv_test;
-- 全量更新物化视图
refresh materialized view mv_test;
-- 再次查询物化视图的数据
select * from mv_test;

Incremental update, incremental update requires a unique identifier to determine which ones are incremental, and there will also be version number constraints on the row data.

-- 查询原来物化视图的数据
select * from mv_test;
-- 增量更新物化视图,因为物化视图没有唯一索引,无法判断出哪些是增量数据
refresh materialized view concurrently mv_test;
-- 给物化视图添加唯一索引。
create unique index index_mv_test on mv_test(id);
-- 增量更新物化视图
refresh materialized view concurrently mv_test;
-- 再次查询物化视图的数据
select * from mv_test;
-- 增量更新时,即便是修改数据,物化视图的同步,也会根据一个xmin和xmax的字段做正常的数据同步

update test set name = '汤圆' where id = 5;
insert into test values (5,'猪头肉',99,40);
select * from test;

Guess you like

Origin blog.csdn.net/a772304419/article/details/132928828
Recommended