鑑於一些表達式返回數據:
select
column1 id,
column2 selected
from (values (2 , 4),(3, 5)) table1;
id | selected
----+----------
2 | 4
3 | 5
(2 rows)
select
column1 id,
column2 rejected
from (values (1 , 12),(3, 13)) table2
dbornside-# ;
id | rejected
----+----------
1 | 12
3 | 13
(2 rows)
通常在ner連接不會產生正確的結果;只有在這兩個關係顯示
select * from
(select column1 id, column2 selected from (values (2 , 4),(3, 5)) table1) table1
join (select column1 id, column2 rejected from (values (1 , 12),(3, 13)) table2) table2
on table1.id = table2.id;
id | selected | id | rejected
----+----------+----+----------
3 | 5 | 3 | 13
(1 row)
要想從右表中的行所有行,你需要一個right outer join
,從左邊行是left outer join
;爲了讓你使用一個full outer join
:
select *
from (select column1 id, column2 selected from (values (2 , 4),(3, 5)) table1) table1
FULL OUTER JOIN (select column1 id, column2 rejected from (values (1 , 12),(3, 13)) table2) table2
on table1.id = table2.id;
id | selected | id | rejected
----+----------+----+----------
2 | 4 | |
3 | 5 | 3 | 13
| | 1 | 12
(3 rows)
雖然這看起來有點奇怪。那是因爲table1.id
與table2.id
不一樣;並且某些值在兩個表中都不存在。我們可以與coalesce()
同一步驟他們聚集:
select COALESCE(table1.id, table2.id) id,
selected,
rejected
from (select column1 id, column2 selected from (values (2 , 4),(3, 5)) table1) table1
full outer join (select column1 id, column2 rejected from (values (1 , 12),(3, 13)) table2) table2
on table1.id = table2.id;
id | selected | rejected
----+----------+----------
2 | 4 |
3 | 5 | 13
1 | | 12
(3 rows)
是SQL Server的'FULL OUTER JOIN' PostgreSQL的'FULL OUTER JOIN'不同? –
@CraigRinger我不好,我以爲'postgresql'不支持'全外連接'。謝謝。我真的很感激它! –