我在postgres中创建了一些表,从一个表添加了一个外键到另一个表,并将ON DELETE设置为CASCADE。奇怪的是,我有一些似乎违反这个约束的领域。
这是正常的行为吗?如果是这样,有没有办法得到我想要的行为(没有违规行为)?
编辑:
我原创创建外键作为CREATE TABLE的一部分,只是使用
... REFERENCES product (id) ON UPDATE CASCADE ON DELETE CASCADE
当前的代码pgAdmin3给出
ALTER TABLE cultivar ADD CONSTRAINT cultivar_id_fkey FOREIGN KEY (id) REFERENCES product (id) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE;
编辑2:
要澄清,我有一个偷偷的怀疑,只有在更新/插入发生时才会检查这些约束,但是再次看不到。不幸的是,我不太了解postgres,以确定这是否是真的,或者如果没有运行这些检查,那么字段可能会在数据库中最终出现。
如果是这种情况,是否有办法检查所有的外键并修复这些问题?
编辑3:
一个限制违规可能是由错误的触发引起的,见下文
我试图创建一个简单的例子,显示外键约束被强制执行。有了这个例子,我证明我不允许输入违反fk的数据,我证明如果fk在插入过程中不到位,并且我启用fk,fk约束会引发一个错误,告诉我数据违反了fk。所以我没有看到你的表中的数据违反了一个fk的位置。我在9.0,但这不应该在8.3不同。如果您可以显示一个证明您可能有帮助的问题的工作示例。
原文链接:https://www.f2er.com/postgresql/193106.html--CREATE TABLES-- CREATE TABLE parent ( parent_id integer NOT NULL,first_name character varying(50) NOT NULL,CONSTRAINT pk_parent PRIMARY KEY (parent_id) ) WITH ( OIDS=FALSE ); ALTER TABLE parent OWNER TO postgres; CREATE TABLE child ( child_id integer NOT NULL,parent_id integer NOT NULL,CONSTRAINT pk_child PRIMARY KEY (child_id),CONSTRAINT fk1_child FOREIGN KEY (parent_id) REFERENCES parent (parent_id) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE ) WITH ( OIDS=FALSE ); ALTER TABLE child OWNER TO postgres; --CREATE TABLES-- --INSERT TEST DATA-- INSERT INTO parent(parent_id,first_name) SELECT 1,'Daddy' UNION SELECT 2,'Mommy'; INSERT INTO child(child_id,parent_id,1,'Billy' UNION SELECT 2,'Jenny' UNION SELECT 3,'Kimmy' UNION SELECT 4,2,'Billy' UNION SELECT 5,'Jenny' UNION SELECT 6,'Kimmy'; --INSERT TEST DATA-- --SHOW THE DATA WE HAVE-- select parent.first_name,child.first_name from parent inner join child on child.parent_id = parent.parent_id order by parent.first_name,child.first_name asc; --SHOW THE DATA WE HAVE-- --DELETE PARENT WHO HAS CHILDREN-- BEGIN TRANSACTION; delete from parent where parent_id = 1; --Check to see if any children that were linked to Daddy are still there? --None there so the cascade delete worked. select parent.first_name,child.first_name from parent right outer join child on child.parent_id = parent.parent_id order by parent.first_name,child.first_name asc; ROLLBACK TRANSACTION; --TRY ALLOW NO REFERENTIAL DATA IN-- BEGIN TRANSACTION; --Get rid of fk constraint so we can insert red headed step child ALTER TABLE child DROP CONSTRAINT fk1_child; INSERT INTO child(child_id,first_name) SELECT 7,99999,'Red Headed Step Child'; select parent.first_name,child.first_name asc; --Will throw FK check violation because parent 99999 doesn't exist in parent table ALTER TABLE child ADD CONSTRAINT fk1_child FOREIGN KEY (parent_id) REFERENCES parent (parent_id) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE; ROLLBACK TRANSACTION; --TRY ALLOW NO REFERENTIAL DATA IN-- --DROP TABLE parent; --DROP TABLE child;