Postgres:检查两个框是否重叠

问题描述 投票:1回答:1

我目前在数据库中有以下表格:

create table map (
    id          bigint          not null unique,
    zone        box             not null,
    ...
    primary key(id)
);

create table other_map (
    id          bigint          not null unique,
    zone        box             not null,
    ...
    primary key(id),
    foreign key(id) references map(id)
);

如果other_map中有一行map等于新条目的id andid,则我不想允许在zone中插入新行。属性重叠。我找到了this answer,它解释了如何检测重叠的框,但是我想知道如何(最好)在Postgres中应用它。

到目前为止,这是我使用触发器和存储过程提出的:

CREATE OR REPLACE FUNCTION PROC_other_map_IU()
RETURNS TRIGGER AS $PROC_other_map_IU$
DECLARE
    id      bigint;
    zone    box;
BEGIN
    SELECT map.id, map.zone INTO id, zone
    FROM map
    WHERE map.id = NEW.id;

    IF zone = NEW.zone THEN
        RAISE EXCEPTION '%\'s zone overlaps with existing %\'s zone', NEW.id, id;
    END IF;

    RETURN NEW;
END;
$PROC_other_map_IU$ LANGUAGE plpgsql;

CREATE TRIGGER TR_other_map_IU
AFTER INSERT OR UPDATE
ON other_map
FOR EACH ROW EXECUTE PROCEDURE PROC_other_map_IU();

现在显然这是错误的,因为它只是检查zone属性是否相等。

谢谢您的输入!干杯!

stored-procedures constraints overlap database-trigger postgresql-9.4
1个回答
0
投票

花了我一段时间,但Postgres的geometric functions and operators(更确切地说是&&-或重叠的-运算符)完全满足了我的要求:

IF zone && NEW.zone THEN
© www.soinside.com 2019 - 2024. All rights reserved.