Answers:
要将列添加到现有表中,请使用ALTER TABLE DDL,例如:
ALTER TABLE my_table
ADD COLUMN the_geom_mercator
geometry(Geometry,3857);
可以使用以下命令从另一列(the_geom)填充:
UPDATE my_table SET
the_geom_mercator = ST_Transform(the_geom, 3857)
FROM spatial_ref_sys
WHERE ST_SRID(the_geom) = srid;
(第三行FROM spatial_ref_sys ...
不是必需的,但它可以保护具有未知或无效投影的转换尝试,从而引发错误)。
如果要维护(添加/更新)该表,则可以使用触发函数来更新the_geom_mercator,例如:
CREATE OR REPLACE FUNCTION my_table_tg_fn() RETURNS trigger AS
$BODY$BEGIN
IF TG_OP = 'INSERT' AND NEW.the_geom ISNULL THEN
RETURN NEW; -- no new geometry
ELSIF TG_OP = 'UPDATE' THEN
IF NEW.the_geom IS NOT DISTINCT FROM OLD.the_geom THEN
RETURN NEW; -- same old geometry
END IF;
END IF;
-- Attempt to transform a geometry
BEGIN
NEW.the_geom_mercator := ST_Transform(NEW.the_geom, 3857);
EXCEPTION WHEN SQLSTATE 'XX000' THEN
RAISE WARNING 'the_geom_mercator not updated: %', SQLERRM;
END;
RETURN NEW;
END;$BODY$ LANGUAGE plpgsql;
CREATE TRIGGER my_table_tg BEFORE INSERT OR UPDATE
ON my_table FOR EACH ROW
EXECUTE PROCEDURE my_table_tg_fn();
请注意,ST_Transform应该捕获错误并显示警告,例如:
postgis=# INSERT INTO my_table(the_geom)
postgis-# VALUES (ST_SetSRID(ST_MakePoint(0,1), 123))
postgis-# RETURNING the_geom, the_geom_mercator;
WARNING: the_geom_mercator not updated: GetProj4StringSPI: Cannot find SRID (123) in spatial_ref_sys
-[ RECORD 1 ]-----+---------------------------------------------------
the_geom | 01010000207B0000000000000000000000000000000000F03F
the_geom_mercator |
INSERT 0 1
shp2psql
并且通过管道创建表psql
。所以我真的不能在表存在之前添加触发器吗?
您可以创建一个不受约束的SRID几何列以保存本机表单,然后转换为现有表单。这是一个人为的示例,假设您要从登台表中复制多边形(如果已混合,则可以将类型设置为几何,例如geometry(Geometry,3857):
CREATE TABLE poi(gid serial primary key,
geom_native geometry(POLYGON),
geom_mercator geometry(POLYGON,3857) );
INSERT INTO TABLE poi(geom_native, geom_mercator)
SELECT geom, ST_Transform(geom, 3857)
FROM staging.imported_poly;
geom
列的表,而我只想添加另一the_geom_webmercator
列。我该怎么办?