2017-02-12 53 views
1

我們如何在多個表中使用左半連接。例如,在SQL中,查詢檢索no。在美國工作的員工是:左半加入蜂巢多表

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' 
       ) 

由於IN查詢蜂房中不支持,怎麼能在蜂巢寫這篇文章。

+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; 

我應該注意到,雖然,「美」不是通常被認爲是一個城市。

編輯:

顯然,如果一個部門只能有一個位置,然後在「半聯接」是沒有必要的。 SELECT DISTINCT只能是SELECT。 。 。或者,您可以像Dudu的回答一樣使用JOIN。無論如何,EXISTS將工作。在許多數據庫中,它會有很好的表現(有時是最好的表現);我不確定Hive中的性能影響。

+0

'distinct'? ...... –

+0

@DuduMarkovitz。 。 。是。一個部門可以(合理地)在同一個城市/國家有多個地點。您的版本將返回重複項。半連接只是簡單地檢查第二個表中是否存在,所以它不能在第一個表中重複行。 –

+0

與此表結構不同的是,'dept'具有'location_id' –

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_idemp不合格(應爲emp.dept_id)。
此作品:

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

嗨,還在嗎? –