公用表表达式

公用表表达式(CTE)是一个临时结果集,它是从 WITH 子句中指定的简单查询派生而来的,该查询紧接在 SELECT 或 INSERT 关键字之前。 CTE 仅在单个语句的执行范围内定义。 Hive SELECTINSERT创建表作为选择创建选择视图语句中可以使用一个或多个 CTE。

Version

在 Hive 0.13.0 中使用HIVE-1180添加了公共表表达式。

公用表表达式语法

withClause: cteClause (, cteClause)*
cteClause: cte_name AS (select statment)

其他语法规则

  • 子查询块中不支持 WITH 子句

  • 视图,CTAS 和 INSERT 语句均支持 CTE。

  • 不支持Recursive Queries

Examples

SELECT 语句中的 CTE

with q1 as ( select key from src where key = '5')
select *
from q1;

-- from style
with q1 as (select * from src where key= '5')
from q1
select *;

-- chaining CTEs
with q1 as ( select key from q2 where key = '5'),
q2 as ( select key from src where key = '5')
select * from (select key from q1) a;

-- union example
with q1 as (select * from src where key= '5'),
q2 as (select * from src s2 where key = '4')
select * from q1 union all select * from q2;

视图,CTAS 和插入语句中的 CTE

-- insert example
create table s1 like src;
with q1 as ( select key, value from src where key = '5')
from q1
insert overwrite table s1
select *;

-- ctas example
create table s2 as
with q1 as ( select key from src where key = '4')
select * from q1;

-- view example
create view v1 as
with q1 as ( select key from src where key = '5')
select * from q1;
select * from v1;

-- view example, name collision
create view v1 as
with q1 as ( select key from src where key = '5')
select * from q1;
with q1 as ( select key from src where key = '4')
select * from v1;

在第二个“视图”示例中,查询的 CTE 与创建视图时使用的 CTE 不同。结果将包含 key ='5'的行,因为在视图的查询语句中,视图定义中定义的 CTE 生效。

另请参阅此 JIRA:

  • HIVE-1180在 Hive 中支持公用表表达式(CTE)