【发布时间】:2017-12-29 18:06:58
【问题描述】:
我有一个配置,thing 可以有多个属性,property 可以属于多个事物:
CREATE TABLE thing (
id integer NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE property (
id integer NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE thingproperty (
thing integer NOT NULL,
property integer NOT NULL
);
ALTER TABLE thingproperty
ADD CONSTRAINT tp_thing
FOREIGN KEY (thing) REFERENCES thing(id)
ON UPDATE CASCADE ON DELETE CASCADE;
ALTER TABLE thingproperty
ADD CONSTRAINT tp_property
FOREIGN KEY (property) REFERENCES property(id)
ON UPDATE CASCADE ON DELETE CASCADE;
我想确保 property 仅在它属于至少一个 thing 时才能存在,为此我编写了这个删除事物的事务(必要时还删除属性),但我没有不知道对不对:
START TRANSACTION;
DELETE FROM thing ... ;
DELETE FROM property
WHERE id NOT IN (
SELECT property
FROM thingproperty
);
COMMIT TRANSACTION;
所以我基本上相信在DELETE FROM thing ... 查询运行后的引擎,它立即应用tp_thing 约束并删除thingproperty 在@ 之前属于已删除thing(s) 的记录987654331@被执行。
这是一种安全的方法吗?
【问题讨论】:
标签: sql postgresql many-to-many constraints cascading-deletes