一、with...as语句说明
wih语句,允许hive定义一个sql片段,供整个sql使用,会将这个片段产生的结果集保存在内存中,后续的sql均可以访问这个结果集,作用与视图或临时表类似。
【注】目前 oracle、sql server、hive等均支持 with as 用法,但 mysql并不支持!
二、注意事项
1、with 语句是一次性的,相当于建立了一张临时虚拟表,但不会被物理创建,用完即销毁
2、每一个with语句,单独成为一个子模块,最后使用基础表将它们串联起来。这里必须要整体作为一条sql查询,即with as语句后不能加分号,不然会报错
3、with as允许跟多个子句,用逗号隔开,最后一个子句与后面的查询语句之间只能用右括号分隔,不能用逗号
sql
create table a as
with t1 as (select * from firstTable),
t2 as (select * from secondTable),
t3 as (select * from thirdTable)
select * from t1,t2,t3;
4、with...as语句必须和其他sql一起使用,如果定义了wih子句,但其后没有跟selec查询,则会报错
sql
with t1 as (select * from table1) -- 该语句执行会报错
-- 正确写法:(没有使用 t1没关系,其后有select就行)
with t1 as (select * from table1)
select * from table1
5、前面的with子句定义的查询在后面的with子句中可以使用。但是一个with子句内部不能嵌套with子句
sql
with t1 as (select * from table1),
t2 as (select t1.id from t1)
select * from t2