如何在postgresql中使用新值更新列

时间:2014-11-16 22:15:25

标签: sql postgresql

我有一个名为nyc的表,它包含3列,id,geom和area.Geom列是几何类型。我想计算表中每个geom的面积和它到nyc表的area列。

我尝试使用以下命令,但它不起作用:

update nyc as p set area=(select st_area(geom) from nyc) where p.id=nyc.id;

它给我一个错误说:

LINE 1: update nyc as p set area=(select st_area(geom) from nyc...
                                       ^
HINT:  You will need to rewrite or cast the expression.

由于id是唯一列,我假设我应该根据id更新列。我有点困惑,我怎么能连续更新值。感谢任何帮助。

由于

2 个答案:

答案 0 :(得分:1)

您可以将UPDATE语句重写为以下内容

update nyc as p 
set area = tab.new_area
from (
select id, st_area(geom) as new_area from nyc
) as tab 
where p.id = tab.id;

答案 1 :(得分:1)

如果id是主键,则不需要任何子选择:

update nyc
   set area = st_area(geom);

这将更新表中的所有行,将area列的现有值替换为新值。

相关问题