【问题标题】:How to create a spatial constraint in a table based on a polygon?如何在基于多边形的表中创建空间约束?
【发布时间】:2020-10-17 11:29:09
【问题描述】:

我有一张表格,可以收集一定区域内的一些测量值。我知道创建此验证的触发器,但我正在寻找更简单的方法,因为我需要验证我的记录的区域是单个多边形。

这是我的表格的简化版本:

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

如何在不使用触发器的情况下在插入之前验证记录?

【问题讨论】:

    标签: postgresql constraints postgis spatial


    【解决方案1】:

    欢迎来到 SO。

    最简单的方法是使用空间函数ST_Contains 和你的这个多边形向你的表添加一个CHECK 约束,例如:

    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).
    

    延伸阅读:PostgreSQL CHECK Constraint

    【讨论】:

      猜你喜欢
      • 2018-12-13
      • 2011-01-13
      • 2019-11-14
      • 2015-08-30
      • 2015-07-01
      • 2011-01-02
      • 1970-01-01
      • 2013-05-21
      • 1970-01-01
      相关资源
      最近更新 更多