我目前在数据库中有以下表格:
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
and其id
,则我不想允许在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
属性是否相等。
谢谢您的输入!干杯!
花了我一段时间,但Postgres的geometric functions and operators(更确切地说是&&
-或重叠的-运算符)完全满足了我的要求:
IF zone && NEW.zone THEN