如何使用null测试更新postgres表?

时间:2017-06-23 11:27:29

标签: sql postgresql

我需要更新表1中的名称和描述,

enter image description here

表2中的值。

enter image description here

如果表2中没有值,则不要用null覆盖表1中的名称或描述。我提出了2个请求并要求他们帮助我优化它们。

更新请求:

UPDATE final
SET
  name        = product_info.name
FROM product_info
WHERE final.xml_id = product_info.xml_id
      AND product_info.name NOTNULL;

UPDATE final
SET
  description        = product_info.description
FROM product_info
WHERE final.xml_id = product_info.xml_id
      AND product_info.description NOTNULL;

1 个答案:

答案 0 :(得分:1)

您可以在一个查询中执行此操作:

UPDATE final f
    SET name = COALESCE(pi.name, f.name),
        description = COALESCE(pi.description, f.description)
FROM product_info pi
WHERE f.xml_id = pi.xml_id AND
      (pi.name IS NOT NULL OR pi.description IS NOT NULL);