PSQL:合并两个数据库表并保留空值

PSQL: Combining two database tables and keep null values

我在 Postgres 数据库中有两个 table。我们称它们为 Results1 和 Results2。 它们包含服务器上的数据。

结果 1 看起来像这样:

Hostname | Name | SystemID | IPAddress | LastCheckin | OSAStatus
----------------------------------------------------------------
aaaa.com | aaaa | 0000001  | xx.xxx.x  | 20150714    | online
bbbb.com | bbbb | 0000002  | xx.xxx.y  | 20150713    | offline
cccc.com | cccc | 0000003  | xx.xxx.z  | 20150614    | online
xxxx.net | xxxx | 0000004  | xx.xxx.1  | 20130301    | unknown

它目前不包含任何空值,但将来总有可能。

table 结果 2 看起来像这样:

Hostname | Name | IPAddress | InventoryDate | Status
----------------------------------------------------------------
aaaa.com | aaaa | xx.xxx.x  | 20130714      | Retired
bbbb.com | bbbb | xx.xxx.y  |               | RunTime
cccc.com | cccc |           | 20150614      | RunTime
         | dddd | xx.xxx.a  | 20150614      | Planned
eeee.com | eeee | xx.xxx.b  |               | Installation
ffff.com | ffff | xx.xxx.c  |               | Retired
gggg.com | gggg | xx.xxx.d  | 20150614      | RunTime

我想做的就是combine/join这两个table,这样我就可以比较数据了。 我想加入他们的名字,因为这是 table 中唯一不能为空的公共值。

我尝试了以下 SELECT 语句:

SELECT Results1.Name, SystemID, LastCheckin, InventoryDate, OSAStatus, Status AS R1Status
FROM Results1
FULL OUTER JOIN
Results2 
ON Results1.Name=Results2.Name
ORDER BY Name;

它部分满足了我的要求,但不完全。我得到的结果是这样的:

Name | SystemID | LastCheckin | InventoryDate | OSAStatus | R1Status
----------------------------------------------------------------
aaaa | 0000001  | 20130714    | 20130714      |  online   | Retired
bbbb | 0000002  | 20150713    |               |  offline  | RunTime
cccc | 0000003  | 20150614    | 20150616      |  online   | RunTime
xxxx | 0000004  | 20130301    |               |  unknown  |
     |          |             |               |           | Planned
     |          |             |               |           | Installation
     |          |             |               |           | Retired
     |          |             | 20150614      |           | RunTime

如你所见。当服务器仅存在于 Results2 中而不存在于 Results1 中时,我会丢失该服务器的 Name 属性,这是一个大问题。 当服务器同时存在于 Results1 和 Results2 中,或仅存在于 Results1 中时,它也可以按我的意愿工作。

我知道我只会 select Results1.Name,但我不知道如何处理它们而不让它们最终出现在不同的列中。

谁能帮我做一个能够处理这个问题的 PSQL 查询?

我认为 IS NOT DISTINCT FROM 可以满足您的要求:

SELECT r1.Name, SystemID, LastCheckin, InventoryDate, OSAStatus, Status AS R1Status
FROM Results1 r1 FULL OUTER JOIN
     Results2 r2
     ON r1.Name IS NOT DISTINCT FROM r2.Name
ORDER BY Name;

您可能还想 select COALESCE(r1.Name, r2.Name) as Name 而不仅仅是 r1.Name.