Hello,大家好,今天为大家分享一份HIVE的多表查询文章,之前我们给大家简单聊了聊HIVE的一些基础操作,但是在我们的实际企业应用中往往没有那么简单容易的,今天就为大家分享一些HIVE的join语句,union all语句以及with语句的用法~

先来看看union all语句的使用

union all语句将俩个表中相同的字段拼接在一起进行表的查询,注意的是union all不去重,数据会重复,我们来看看网络上的一些案例~

--准备表create external table IF NOT EXISTS temp_uniontest_ta(a1 string,a2 string)partitioned by (dt string)row format delimited fields terminated by '\t'stored as textfile;ALTER TABLE temp_uniontest_ta ADD IF NOT EXISTS PARTITION (dt = '2014-10-13') location '/temp/unionTest/ta/';a1  a2  2014-10-13b1  b2  2014-10-13c1  c2  2014-10-13 create external table IF NOT EXISTS temp_uniontest_tb(a1 string,a2 string)partitioned by (dt string)row format delimited fields terminated by '\t'stored as textfile;ALTER TABLE temp_uniontest_tb ADD IF NOT EXISTS PARTITION (dt = '2014-10-13') location '/temp/unionTest/tb/';d1  d2  2014-10-13e1  e2  2014-10-13
-- 进行union all查询select * from (select a1,a2 from temp_uniontest_ta where dt = '2014-10-13'union allselect a1,a2 from temp_uniontest_tb where dt = '2014-10-13') tmp;a1  a2b1  b2c1  c2d1  d2e1  e2

上面是我们的union all连接,接下来我们看看hive的join连接

在这里要注意的是Hive只支持等值连接(equality joins)、外连接(outer joins)和(left/right joins)。Hive 不支持所有非等值的连接,因为非等值连接非常难转化到 map/reduce 任务。另外,Hive 支持多于 2 个表的连接。join关联查询实例如下:

Hive 一次扫表多次 hive 多表查询_hive sql练习

innser join(join)查询

selecta.name as aname,a.numb as anumb,b.name as bname,b.nick as bnickfrom t_a ajoin t_b bon a.name=b.name

Hive 一次扫表多次 hive 多表查询_Hive 一次扫表多次_02

left outer join(left join)查询

select    a.name as aname,    a.numb as anumb,    b.name as bname,    b.nick as bnickfrom t_a aleft outer join t_b bon a.name=b.name

Hive 一次扫表多次 hive 多表查询_left join 和子查询效率_03

full outer join(full join)查询

Hive 一次扫表多次 hive 多表查询_left join 和子查询效率_04

left semi join查询

hive中不支持exist/IN子查询,可以用left semi join来实现同样的效果:

selecta.name as aname,a.numb as anumbfrom t_a aleft semi join t_b bon a.name=b.name;

Hive 一次扫表多次 hive 多表查询_hive if语句_05

注意: left semi join的 select子句中,不能有右表的字段

上述是我们常用的join查询,接下来我们看看我们最常用的with语法:

为啥要说with呢,首先我们用的很多,贼多,hive可以通过with查询来提高查询性能,因为先通过with语法将数据查询到内存,然后后面其他查询可以直接使用~案例如下:

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;--上述代码中q1是一张表,q2也是一张表,这样我们就可以讲复杂的sql语句简化一部分,个人觉得特别好用
--插入操作实例create table s1 like src;with q1 as ( select key, value from src where key = '5')from q1insert overwrite table s1select *;

基础的语法就如上所示啦,在实际应用中我们一般会将with,union all,if,统计函数,group by 等结合起来一起操作,一条sql56十行都是正常的,所以建议大家打好基础方便后期的使用~~~~