create table agg_source(
id UInt8,
name String,
city String,
money UInt32
)engine=MergeTree()
partition by city
order by id;
insert into agg_source values
(1, 'aa', 'SD', 200),
(2, 'bb', 'SD', 200),
(3, 'cc', 'SH', 200),
(4, 'dd', 'BJ', 200),
(5, 'ee', 'SZ', 200),
(6, 'ff', 'BJ', 100);
(7, 'gg', 'HZ', 100);
(8, 'ww', 'WH', 100);
执行查询
select
city,
uniq(name) num,
sum(money) money
from agg_source
group by city;
create materialized view agg_view
engine = AggregatingMergeTree()
partition by city
order by city
populate
as
select
city,
uniqState(name) name,
sumState(money) money
from agg_source
group by city;
执行查询
select
city,
uniqMerge(name),
sumMerge(money)
from agg_view
group by city;
populate 表示实时同步源表数据的变化,会影响性能。如果不加,则会在合并分区或者手动执行 optimeize table 的时候更新视图中的数据。
物化视图可以理解为预计算,聚合函数的值提前在物化视图中已经计算好了,查询的时候就直接拿值就好了,提高了查询的速度,当然物化视图也占用本地磁盘空间,相当于空间换时间,并且源表数据变化物化视图也会跟着修改,所以要尽可能减少修改操作。