更新每一行中具有不同值的列

时间:2019-11-30 12:52:13

标签: sql postgresql join sql-update

id_location列的每一行都有不同的值。 到目前为止,我已经尝试过:

UPDATE Apartment  
         Join Location 
         On
         Apartment.id_location= Location.id_location;
        SET Apartment.state = Location.state;

谢谢。 注意:id_location是来自位置的FK(其中id_lcoation是PK)。另外,我不能使用INSERT INTO,因为它花费了很多时间。我也在用postgres

2 个答案:

答案 0 :(得分:0)

Postgres具有用于执行更新连接的特定语法:

UPDATE Apartment a
SET state = l.state
FROM Location l
WHERE a.id_location= l.id_location;

您还可以使用相关子查询进行更新:

UPDATE Apartment a
SET state = (SELECT l.state FROM Location l WHERE a.id_location= l.id_location)
WHERE EXISTS
    (SELECT 1 FROM Location l WHERE a.id_location= l.id_location);

答案 1 :(得分:0)

Tim关于语法是正确的。

但是,您应该修复数据模型。您不应在两个不同的表中重复该状态。相反,您可以在需要时查找state

select a.*, l.state
from apartment a join
     location l
     using (id_location);

保证“公寓”始终处于该位置所建议的正确状态。

如果经常需要此信息,请使用视图:

create view v_apartments as
    select a.*, l.state
    from apartment a join
         location l
         using (id_location);