with as 和临时表的使用

with as 和建临时表的区别

with as (公共表达式CTE)

当我们书写一些比较结构复杂,用的表也很多的sql时,可以用with as。
with as 是子查询部分,并不是真正的临时表,查询结果保存在内存中。定义一个sql片段,该片段在整个sql都可以被利用,可以提高代码的可读性以及减少重复读,减少性能成本。

with table1 as
select one,tow,thire
from A

table2 as
select one,five
from B

insert overwrite table AB  partition(dt={'hiveconf:dt'})
select one,tow,thire,four,five
from A left join B on A.one = B.one

注意:后面必须直接紧跟使用CTE的SQL语句,否则失效

临时表

数据库临时表和永久表类似,储存在磁盘的临时区中,只有数据库连接断开,或者drop掉,才会消失。

drop table if exists tmp.table1;
create table tmp.table1 stored as orc as
select one,tow,thire
from A

drop table if exists tmp.table2;
create table tmp.table2 stored as orc as
select one,five
from B

insert overwrite table AB  partition(dt={'hiveconf:dt'})
select one,tow,thire,four,five
from A left join B on A.one = B.one

使用技巧

1.来源于一张表的不同维度的数据,也倾向于在一次with as中收集齐全,命更高层次上抽象主题。避免同一张底表在多个with as中存在。
2.在数仓开发之前,先理清楚需要用到的表以及字段,思考清楚以什么结构去开发,思考性能瓶颈是哪里。最好用白纸写清楚。磨刀不误砍柴工。
3.表的连接:
3.1优先汇总之后再连接
3.2汇总维度相同,巧用union,不用join。取各个临时表所需的字段,收集齐全后,一次group by。

发布了3 篇原创文章 · 获赞 1 · 访问量 78

猜你喜欢

转载自blog.csdn.net/GONEW33/article/details/103946578