Hive学习笔记:with as子查询

一、说明

与其他 SQL 语法类似,Hive 中也支持 with as 将一大段 SQL 语句封装为子查询,方便后续多次调用。

MySQL旧版本不支持with as语法,8.0才支持。

with tt as
(
	select *,
            row_number() over(partition by id order by score desc) rn 
    from table_name
)
select * from tt where rn = 1;

Hive 可以通过 with 查询来提高查询性能,因为先通过 with 语句将数据查询到内存中,后续查询可以直接调用。

类似于视图、临时表,不过是一次性的,但是可以大大简化后续SQL。

二、注意

1.with 子句必须在引用的 select 语句之前定义,而且后面必须要跟 select 查询,否则报错。

2.with as 后面不能加分号,with 关键字在同级中只能使用一次,允许跟多个子句,用逗号隔开,最后一个子句与后面的查询语句之间只能用右括号分隔,不能用逗号。

create table table_new as
with t1 as
(
	select * from table_first
),
t2 as
(
	select * from table_seconde
),
t3 as
(
	select * from table_third
)
select * from t1, t2, t3;

3.前面的 with 子句定义的查询在后面的 with 子句中可以使用。但是一个 with 子句内部不能嵌套 with 子句。

with t1 as
(
	select * from table_first
),
t2 as
(
	select * from t1
)
select * from t2;

参考链接:Hive(二):with as用法

参考链接:Hive中使用 with as 优化SQL

posted @ 2022-11-19 21:35  Hider1214  阅读(1656)  评论(0)    收藏  举报