【问题标题】:Basic Postgres: How do I insert a value into all rows?基本 Postgres:如何将值插入所有行?
【发布时间】:2015-02-10 13:09:29
【问题描述】:

很抱歉提出这样一个基本问题(我确定它是重复的),但我已经进行了广泛的搜索,但我无法弄清楚如何做我需要的事情。我可能只是在搜索错误的关键字。

我有一个空列的数据库表。我想在该列中为所有行插入一个值。

我的桌子是这样的:

 wkb_geometry | geometry(Polygon,4326) |
 id           | integer                |
 area         | real                   |

我想将wkb_geometry 的区域插入到所有行的区域列中。

我知道如何计算和更新单个行,如下所示:

update inspire_parcel set area=(select st_area(wkb_geometry::geography) 
  from inspire_parcel where id=24045271) where id=24045271;

但我怎样才能对所有行执行此操作?

如果它有所作为,我有很多行 - 超过 2000 万行。

【问题讨论】:

  • 为什么不保持简单呢?试试:update inspire_parcel set id = 24045271 where id = NULL;如果不设置为NULL试试,update inspire_parcel set id = 24045271 where id = '';

标签: sql postgresql sql-update dml


【解决方案1】:

不需要select,只用函数的结果更新列,省略where子句来更新所有行:

update inspire_parcel 
   set area = st_area(wkb_geometry::geography);

为避免覆盖现有值,只需使用适当的 WHERE 子句:

update inspire_parcel 
   set area = st_area(wkb_geometry::geography)
where area is null;

如果你只想为单行做这也是正确的方法:

update inspire_parcel 
   set area = st_area(wkb_geometry::geography)
where id = 24045271;

【讨论】:

  • 谢谢@a_horse_with_no_name!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 2021-10-11
  • 1970-01-01
相关资源
最近更新 更多