Postgresql:尝试使用自连接替换空值并最终用第一个结果替换整个列

Postgresql: Trying to replace null values using a self join and ending up replacing entire column with first result

在匹配的 parcelid 上创建了自连接,并使用匹配的 parcelid 填充缺失的空值。但是,在使用 UPDATE 函数后,它会将 property_address 中的每一行替换为第一个结果。

UPDATE housing
SET property_address = COALESCE(a.property_address, b.property_address)
FROM housing AS a
JOIN housing AS b
    ON a.parcelid = b.parcelid
    AND a.unique_id <> b.unique_id
WHERE a.property_address is null

您只需要 housing 的 2 个副本,因此删除多余的连接。
同样在WHERE子句中添加条件,使更新后的值不为空:

UPDATE housing AS h1
SET property_address = h2.property_address
FROM housing AS h2
WHERE h1.parcelid = h2.parcelid AND h1.unique_id <> h2.unique_id
  AND h1.property_address IS NULL AND h2.property_address IS NOT NULL