Hive (25): Subqueries subquery of Select advanced query

1 subquery in the from clause

In version 0.12 of Hive, subqueries are only supported in the FROM clause. And you must give the subquery a name, because each table in the FROM clause must have a name.

Columns in the results returned by a subquery must have unique names. The columns returned by the subquery are available in the outer query just like the columns of the real table. Subqueries can also be query expressions with UNION. Hive supports arbitrary levels of subqueries, also known as nested subqueries.

Subquery names in Hive 0.13.0 and later can be preceded by the optional keyword "AS".

--from子句中子查询(Subqueries)
--子查询
SELECT num
FROM (
         select num,name from student_local
     ) tmp;

--包含UNION ALL的子查询的示例
SELECT t3.name
FROM (
         select num,name from student_local
         UNION distinct
         select num,name from student_hdfs
     ) t3;

2 subquery in where clause

Starting with Hive 0.13, the WHERE clause supports certain types of subqueries.

--where子句中子查询(Subqueries)
--不相关子查询,相当于IN、NOT IN,子查询只能选择一个列。
--(1)执行子查询,其结果不被显示,而是传递给外部查询,作为外部查询的条件使用。
--(2)执行外部查询,并显示整个结果。  
SELECT *
FROM student_hdfs
WHERE student_hdfs.num IN (select num from student_local limit 2);

--相关子查询,指EXISTS和NOT EXISTS子查询
--子查询的WHERE子句中支持对父查询的引用
SELECT A
FROM T1
WHERE EXISTS (SELECT B FROM T2 WHERE T1.X = T2.Y);

Guess you like

Origin blog.csdn.net/u013938578/article/details/131666039