【问题标题】:How to update single row using multiple tables?如何使用多个表更新单行?
【发布时间】:2020-11-18 00:14:47
【问题描述】:

我有 3 个表格,例如:

animals: id, code, address
dogs: id,code, address
cats: id,code, address

动物包含来自狗和猫的数据等等。 动物表中的某些行具有 NULL 地址值,我想用猫和狗的地址值更新它,如下所示:

UPDATE animals
SET address = coalesce(cats.address,dogs.address)
FROM dogs
left join cats on cats.id = dogs.id

但我不确定 JOIN 在那里可以正常工作。 如何组合 cat 和 dogs 表中的地址值? 或者我需要一一更新?

【问题讨论】:

    标签: sql postgresql join sql-update left-join


    【解决方案1】:

    这里有一种表达方式:

    update animals a
    set address = coalesce(c.address, d.address)
    from animals a1
    left join dogs d on d.id = a1.id
    left join cats c on c.id = a1.id
    where a.id = a1.id
    

    根据您的实际设置,最好确保任一表中至少有一个匹配项:

    update animals a
    set address = coalesce(c.address, d.address)
    from animals a1
    left join dogs d on d.id = a1.id
    left join cats c on c.id = a1.id
    where a.id = a1.id and (d.id is not null or c.id is not null)
    

    【讨论】:

    • 如果原始海报不清楚:您希望在 FROM 中包含动物的原因是因为在您的原始查询中,如果 dogs 表中没有特定动物 ID 的行,则该行即使有 cat 行,也不会更新,因为 LEFT 连接只会无条件地从左侧表中发出行。您可以通过使用 FULL 连接或将 LEFT 连接的左侧作为原始表来解决这个问题,正如 GMB 在这里所做的那样(我也更喜欢这种方式而不是 FULL 连接;它更易于阅读并理解)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多