给定一些返回数据的表达式:
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)
通常的内连接不会产生正确的结果;仅显示两个关系中的行
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)
要从右侧表中获取所有行,您需要 a right outer join
,左侧的行是 a 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
并且某些值在两个表中都不存在。我们可以在同一步骤中使用 a 将它们收集在一起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)