如何基于多边形在 table 中创建空间约束?
How to create a spatial constraint in a table based on a polygon?
我有一个 table 可以收集一些必须在特定区域内的测量值。我知道创建此验证的触发器,但我正在寻找更简单的东西,因为我需要验证我的记录的区域是一个多边形。
这是我的table的简化版本:
CREATE TABLE measurements (
m_time timestamp,
temperature int,
geom geometry (point,4326)
);
所有插入的记录必须在以下多边形内
POLYGON((-35.32 -7.96,-35.27 -7.96,-35.27 -8.01,-35.32 -8.01,-35.32 -7.96))
一些示例数据:
INSERT INTO measurements VALUES
('2020-06-26 13:30:08',31,'SRID=4326;POINT(-35.29 -7.98)'),
('2020-06-26 12:27:42',34,'SRID=4326;POINT(-35.29 -7.99)'),
('2020-06-26 12:27:42',34,'SRID=4326;POINT(-35.35 -8.0)'); -- this point lies outside of the polygon
如何在不使用触发器的情况下在插入之前验证记录?
欢迎来到 SO。
最简单的方法是用你的这个多边形添加一个 CHECK
constraint to your table using the spatial function ST_Contains
,例如:
ALTER TABLE measurements
ADD CONSTRAINT check_location
CHECK(
ST_Contains('SRID=4326;POLYGON((-35.32 -7.96,-35.27 -7.96,-35.27 -8.01,-35.32 -8.01,-35.32 -7.96))',geom));
插入前两条记录将起作用:
INSERT INTO measurements VALUES
('2020-06-26 13:30:08',31,'SRID=4326;POINT(-35.29 -7.98)'),
('2020-06-26 12:27:42',34,'SRID=4326;POINT(-35.29 -7.99)');
INSERT 0 2
但如果给定点位于多边形之外,则失败:
INSERT INTO measurements VALUES
('2020-06-26 12:27:42',34,'SRID=4326;POINT(-35.35 -8.0)');
ERROR: new row for relation "measurements" violates check constraint "check_location"
DETAIL: Failing row contains (2020-06-26 12:27:42, 34, 0101000020E6100000CDCCCCCCCCAC41C000000000000020C0).
我有一个 table 可以收集一些必须在特定区域内的测量值。我知道创建此验证的触发器,但我正在寻找更简单的东西,因为我需要验证我的记录的区域是一个多边形。
这是我的table的简化版本:
CREATE TABLE measurements (
m_time timestamp,
temperature int,
geom geometry (point,4326)
);
所有插入的记录必须在以下多边形内
POLYGON((-35.32 -7.96,-35.27 -7.96,-35.27 -8.01,-35.32 -8.01,-35.32 -7.96))
一些示例数据:
INSERT INTO measurements VALUES
('2020-06-26 13:30:08',31,'SRID=4326;POINT(-35.29 -7.98)'),
('2020-06-26 12:27:42',34,'SRID=4326;POINT(-35.29 -7.99)'),
('2020-06-26 12:27:42',34,'SRID=4326;POINT(-35.35 -8.0)'); -- this point lies outside of the polygon
如何在不使用触发器的情况下在插入之前验证记录?
欢迎来到 SO。
最简单的方法是用你的这个多边形添加一个 CHECK
constraint to your table using the spatial function ST_Contains
,例如:
ALTER TABLE measurements
ADD CONSTRAINT check_location
CHECK(
ST_Contains('SRID=4326;POLYGON((-35.32 -7.96,-35.27 -7.96,-35.27 -8.01,-35.32 -8.01,-35.32 -7.96))',geom));
插入前两条记录将起作用:
INSERT INTO measurements VALUES
('2020-06-26 13:30:08',31,'SRID=4326;POINT(-35.29 -7.98)'),
('2020-06-26 12:27:42',34,'SRID=4326;POINT(-35.29 -7.99)');
INSERT 0 2
但如果给定点位于多边形之外,则失败:
INSERT INTO measurements VALUES
('2020-06-26 12:27:42',34,'SRID=4326;POINT(-35.35 -8.0)');
ERROR: new row for relation "measurements" violates check constraint "check_location"
DETAIL: Failing row contains (2020-06-26 12:27:42, 34, 0101000020E6100000CDCCCCCCCCAC41C000000000000020C0).