2016-11-04 36 views
1

鑑於表1:蜂巢外連接和非平等條件

id begin_date end_date  foo 
1 2016-01-01 2016-12-31 1 
1 2017-01-01 2017-12-31 2 

和Table 2:

id event_date bar 
1 2016-01-01 100 

我想:

id begin_date end_date foo bar 
    1 2016-01-01 2016-12-31 1 100 
    1 2017-01-01 2017-01-01 2 NULL 

通常情況下,我只是做了一個外加入:

... 
table1 
left join table2 
on table1.id = table2.id 
    and table2.event_date between table1.begin_date and table1.end_date 

但Hive不會允許我們這樣做。所以我試圖向下移動日期比較的where子句,並添加OR event_date is null

... 
table1 
left join table2 
on table1.id = table2.id 
where 
(table2.event_date is null OR 
table2.event_date between table1.start_date and table1.end_date) 

但它是結束了工作就像一個內部聯接,這樣我就不會得到2017年排後面。我做錯了什麼,還是有另一種方法來解決這個問題?

+0

左連接 - >左外連接 –

+0

對不起,不是你的意思是知道什麼。 'LEFT JOIN'和'LEFT OUTER JOIN'是一回事。 – Andrew

+0

你是對的,我會解釋一下在答案中會發生什麼 –

回答

0

,因爲你在where條款砸你沒有得到2017年的行 - 該行不會得到在event_date一個null和日期,條件也是假的。

追隨你的例子,如果你想bar爲空 - 你需要的條件移至SELECT子句:

select t1.id, begin_date, end_date, foo, 
    if(table2.event_date is not null and 
     table2.event_date between table1.start_date and table1.end_date, bar, null) from 
table1 left join table2 
on table1.id = table2.id;