左半连接在Hive中加入多个表

时间:2017-02-12 14:32:33

标签: sql hadoop hive hiveql

我们如何在多个表中使用左半连接。例如,在SQL中查询没有。在美国工作的员工是:

select name,job_id,sal 
from emp 
where dept_id IN (select dept_id 
                  from dept d 
                       INNER JOIN Location L 
                       on d.location_id = L.location_id 
                       where L.city='US'
                  )

由于Hive不支持IN查询,我们如何在Hive中编写它。

2 个答案:

答案 0 :(得分:0)

改为使用exists

select e.name, e.job_id, e.sal 
from emp e
where exists (select 1
              from dept d join
                   location L 
                   on d.location_id = L.location_id 
              where l.city = 'US' and d.dept_id = e.dept_id
             );

您可以参考documentation,其中包含WHERE子句中的子查询。

此查询似乎正在回答以下问题:哪些员工在位于美国的部门工作。您也可以使用子查询在FROM子句中执行此操作;

select e.name, e.job_id, e.sal 
from emp e join
     (select distinct d.dept_id
      from dept d join
           location L 
           on d.location_id = L.location_id 
      where l.city = 'US'
     ) d
     on d.dept_id = e.dept_id;
但是,我应该注意到,#34; US"通常不被认为是一个城市。

编辑:

显然,如果一个部门只能有一个地点,那么"半连接"没有必要。 SELECT DISTINCT只能是SELECT。 。 。或者,您可以使用Dudu的答案中的JOIN s。在任何情况下,EXISTS都可以。在许多数据库中它会很好(有时是最佳性能);我不确定Hive中的性能影响。

答案 1 :(得分:0)

看起来像一个简单的内部联接

select  e.name
       ,e.job_id
       ,e.sal 

from                emp         as e

        join        dept        as d

        on          d.dept_id = 
                    e.dept_id

        join        location    as l

        on          l.location_id   =  
                    d.location_id

where   l.city='US' 

P.S。

Hive确实支持IN

您的查询唯一的问题是dept_id的{​​{1}}不合格(应为emp)。
这有效:

emp.dept_id