我有兩個查詢從三個表拉:選擇另一列加入
t1 -sites
t2 - blues
t3 - reds
QUERY1 -
SELECT s.site_name b.year b.value
FROM sites s, blues b
WHERE s.id = b.site_id AND s.site_name ='site1'
返回以下
(如)| site_name | year | blues |
| site1 | 2012 | 23.6 |
| site1 | 2011 | 19.1 |
| site1 | 2010 | 10.2 |
| site1 | 2009 | 25.8 |
| site1 | 2008 | 14.0 |
查詢2
SELECT s.site_name r.year r.value
FROM sites s, reds r
WHERE s.id = r.site_id
AND s.site_name ='site1'
返回:
| site_name | year | reds |
| site1 | 2012 | 14.0 |
| site1 | 2010 | 11.0 |
| site1 | 2009 | 18.9 |
我最終想要的:
| site_name | year | blues | reds |
| site1 | 2012 | 23.6 | 14.0 |
| site1 | 2011 | 19.1 | |
| site1 | 2010 | 10.2 | 11.0 |
| site1 | 2009 | 25.8 | 18.9 |
| site1 | 2008 | 14.0 | |
這基本上相當於在兩個藍色的所有記錄,紅魔錶網站,多年匹配即使當一個表格沒有該年的記錄。
非常感謝@vkp指着我在正確的方向:熱膨脹係數救援。
下面是測試查詢
WITH x AS (SELECT s.site_name AS name, b.year AS yr1, b.value AS blue_val
FROM public.sites s JOIN public.blues b
ON s.id = b.site_id
WHERE s.site_name = 'Site1'
), y AS (SELECT s.site_name, r.year AS yr2, r.value AS red_val
FROM public.stations s JOIN public.reds r
ON s.id = r.site_id
WHERE s.site_name = 'Site1'
)
SELECT x.name, x.yr1, x.blue_val, y.red_val
FROM x LEFT JOIN y ON x.yr1 = y.yr2
你真的應該習慣了明確的'JOIN's而不是隱加入where子句中 –