将计数值插入表的列中

时间:2014-11-17 00:13:59

标签: sql postgresql postgis

我有两个表,一个有一个点列表,另一个有多边形列表。我发现每个多边形中有多少个点。我希望我找到了计数(*),但我不知道如何将它插入到表中名为total_num的新行中:

所以这是例如。表1-点,表2 - 聚。

指向the_geom列,包含所有点几何数据和 poly有一个带有所有多边形几何数据的id,geom列。

我能够使用以下方法找到toatl_num(每个多边形内的点数):

select count(*) as total 
from points, poly 
where st_contains(poly.geom,points.the_geom) 
group by poly.id;

我根据Id(在poly表中唯一)对它们进行分组。我希望这是对的(如果不正确,请发表评论)。现在我该如何获取这个总数并将其插入表poly?

中名为total_num的列中

我试过了:

update poly 
set total_num=select count(*) as total 
from points, poly 
where st_contains(poly.geom,points.the_geom)
group by poly.id;

表 - 点:

the_geom
---------
 0101000020D708000000000000E8282F4100000000F0BB0D41
 0101000020D7080000000000006C892E410000000040170341
 0101000020D7080000000000003EB82F4100000000A8660641
 0101000020D708000000000000FA792E4100000000D01A0641
 0101000020D708000000000000821F2F410000000028500841
 0101000020D70800000000000004A32F4100000000B8B90241



Table - poly
------------

id  | geom | total_num

1   |(geom consist of geometrical representation of polygon
2   | which can not be entered here because its too long)
3   |
4   |
5   |
6   |

但这给了我一个错误! 感谢

1 个答案:

答案 0 :(得分:1)

使用INNER Join代替Subquery

UPDATE poly 
SET    total_num=B.total 
FROM  (        SELECT   Count(*) AS total ,poly.ID
                FROM     points, 
                         poly 
                WHERE    St_contains(poly.geom,points.the_geom) 
                GROUP BY poly.id) B 
where poly.id = B.id