Postgresql Postgres:复杂的级联问题-确保只删除唯一的外键引用?

Postgresql Postgres:复杂的级联问题-确保只删除唯一的外键引用?,postgresql,Postgresql,我在Postgres数据库中有一些链接表,如下所示: Table "public.key" Column | Type | Modifiers --------+------+----------- id | text | not null name | text | Referenced by: TABLE "enumeration_value" CONSTRAINT "enumeration_value_key_id_fkey" FOREIGN KEY

我在Postgres数据库中有一些链接表,如下所示:

    Table "public.key"
 Column | Type | Modifiers 
--------+------+-----------
 id     | text | not null
 name   | text | 
Referenced by:
    TABLE "enumeration_value" CONSTRAINT "enumeration_value_key_id_fkey" FOREIGN KEY (key_id) REFERENCES key(id)

Table "public.enumeration_value"
 Column | Type | Modifiers 
--------+------+-----------
 id     | text | not null
 key_id | text | 
Foreign-key constraints:
    "enumeration_value_key_id_fkey" FOREIGN KEY (key_id) REFERENCES key(id)
Referenced by:
    TABLE "classification_item" CONSTRAINT "classification_item_value_id_fkey" FOREIGN KEY (value_id) REFERENCES enumeration_value(id)

Table "public.classification_item"
     Column     | Type | Modifiers 
----------------+------+-----------
 id             | text | not null
 transaction_id | text | 
 value_id       | text | 
Foreign-key constraints:
    "classification_item_transaction_id_fkey" FOREIGN KEY (transaction_id) REFERENCES transaction(id)
    "classification_item_value_id_fkey" FOREIGN KEY (value_id) REFERENCES enumeration_value(id)
我想

  • 删除与某笔交易相关的所有分类项目
  • 删除与那些
    分类\u项目相关的所有
    枚举\u值
  • 最后,删除与那些
    枚举值相关联的所有
困难在于
项不是与特定
事务
关联的
枚举值
所独有的。它们是独立创建的,可以跨多个事务存在

因此,我知道如何执行其中的后两个步骤,但不知道第一个步骤:

delete from key where id in (select key_id from enumeration_value where id in (select value_id from "classification_item" where id = (select id from "transaction" where slice_id = (select id from slice where name = 'barnet')))); 
# In statement above: help! How do I make sure these keys are ONLY used with these values?
delete from enumeration_value where id in (select value_id from "classification_item" where id = (select id from "transaction" where slice_id = (select id from slice where name = 'barnet')));
delete from classification_item where transaction_id in (select id from "transaction" where slice_id = (select id from slice where name = 'barnet'));
如果postgres有一个级联删除语句

要是postgres有一个级联删除就好了 声明


从8.0版(5年前)开始,PostgreSQL很长一段时间都有这个选项

也有(2003年发布)。如果不是在早期版本中,我会感到惊讶。没有查看7.4文档;)唉,这没用,因为它不是我的数据库——我继承了它,我没有从头开始重建它的选择。那么,当真正的问题是你的数据模型,你不想修复它的时候,你为什么还要抱怨PostgreSQL呢?这不是火箭科学,你现在只需要修复给你带来问题的部分。说得好,但我不确定你所说的“修复”是什么意思。如果你的意思是删除所有数据并从头开始重新创建数据库,不幸的是,出于各种原因,这不是一个选项。我的问题也可能重复。这是不同的,因为我在问如何检查外键是否唯一。