我正在使用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,但它仍然無法正常工作。
任何建議表示讚賞。
哇,如此快速的解決方案,它的工作。非常感謝。 –
嗨斯特凡諾,萬一我想要避免空值,我該如何用文本替換null,應該是「n/a」或「undefined」 –
好的,我找到了解決方案。 http://stackoverflow.com/questions/27479180/using-coalesce-to-handle-null-values-in-postgresql –