2017-05-17 22 views
0

我正在使用Postgresql來查詢數據。如何連接2個表以獲取左表的更多數據

我已經按以下步驟進行:

表1:

#id #zone_id #name #timestamp_create 
1 1   Alex 2016-08-10 11:00:11.07+00 
2 1   James 2016-08-10 11:30:11.07+00 
3 1   Mary 2016-08-10 11:45:11.07+00 
4 1   Ken  2016-08-10 12:15:11.07+00 
5 1   Aston 2016-08-10 12:45:11.07+00 
6 2   Tom  2016-08-11 11:28:11.07+00 
7 2   Edward 2016-08-11 11:30:11.07+00 

表2:

#id #zone_id #code #timestamp_start   #timestamp_end 
1 1   A  2016-08-10 10:50:11.07+00 2016-08-10 11:15:11.07+00 
2 1   B  2016-08-10 11:16:11.07+00 2016-08-10 11:50:11.07+00 
3 2   E  2016-08-11 10:30:11.07+00 2016-08-11 10:30:11.07+00 

我的查詢:

SELECT t1.zone_id, t1.name, t2.code, t1.timestamp_create 
FROM table1 as t1 INNER JOIN table2 as t2 ON t1.zone_id = t2.zone_id 
WHERE t1.timestamp_create BETWEEN t2.timestamp_start AND t2.timestamp_end 

結果:

#zone_id #name #code #timestamp_create 
1   Alex A  2016-08-10 11:00:11.07+00 
1   James B  2016-08-10 11:30:11.07+00 
1   Mary B  2016-08-10 11:45:11.07+00 

我如何能實現以下結果:

#zone_id #name #code #timestamp_create 
1   Alex A  2016-08-10 11:00:11.07+00 
1   James B  2016-08-10 11:30:11.07+00 
1   Mary B  2016-08-10 11:45:11.07+00 
1   Ken    2016-08-10 12:15:11.07+00 
1   Aston   2016-08-10 12:45:11.07+00 

我也嘗試過使用LEFT OUTER JOIN,但它仍然無法正常工作。

任何建議表示讚賞。

回答

1

簡單地切換到left join不會工作,因爲你有你的where的條件,涉及的右列表。對於不匹配的行,這些列將包含null,因此它們不會滿足條件。

達到你想要什麼,你必須切換到left join並移動條件的on條款

SELECT t1.zone_id, 
     t1.name, 
     t2.code, 
     t1.timestamp_create 
FROM table1 as t1 
LEFT JOIN 
     table2 as t2 
ON  t1.zone_id = t2.zone_id AND 
     t1.timestamp_create BETWEEN t2.timestamp_start AND t2.timestamp_end 
+0

哇,如此快速的解決方案,它的工作。非常感謝。 –

+0

嗨斯特凡諾,萬一我想要避免空值,我該如何用文本替換null,應該是「n/a」或「undefined」 –

+1

好的,我找到了解決方案。 http://stackoverflow.com/questions/27479180/using-coalesce-to-handle-null-values-in-postgresql –

0

你想要一個left join,但你必須移動條件的on條款:

SELECT t1.zone_id, t1.name, t2.code, t1.timestamp_create 
FROM table1 t1 LEFT JOIN 
    table2 t2 
    ON t1.zone_id = t2.zone_id AND 
     t1.timestamp_create BETWEEN t2.timestamp_start AND t2.timestamp_end 
+0

你錯過了'LEFT'在查詢 –

+0

感謝戈登,我得到了點。 –