我正在为postgres手动构造一个DELETE CASCADE语句.

我有一个"事务"和一个"切片"表,如下所示:

    Table "public.slice"
  Column  | Type | Modifiers 
----------+------+-----------
 id       | text | not null
 name     | text | 
Referenced by:
    TABLE "transaction" CONSTRAINT "transaction_slice_id_fkey" FOREIGN KEY (slice_id) REFERENCES slice(id)
 Table "public.transaction"
  Column  | Type | Modifiers 
----------+------+-----------
 id       | text | not null
 slice_id | text | 
Referenced by:
    TABLE "classification_item" CONSTRAINT "classification_item_transaction_id_fkey" FOREIGN KEY (transaction_id) REFERENCES transaction(id)
Table "public.classification_item"
     Column     | Type | Modifiers 
----------------+------+-----------
 id             | text | not null
 transaction_id | text | 
Foreign-key constraints:
    "classification_item_transaction_id_fkey" FOREIGN KEY (transaction_id) REFERENCES transaction(id)

假设我想删除名称为"my_slice"的切片引用的所有事务和分类_项.我需要写什么?

=# delete from classification_item where transaction_id= #...? 
=# delete from transaction where slice_id= #...? 
=# delete from slice where name='my_slice';

推荐答案

如果你不能按照别人的建议做:

begin;
delete from classification_item where transaction_id in (select id from "transaction" where slice_id = (select id from slice where name = 'my_slice'));
delete from "transaction" where slice_id in (select id from slice where name='my_slice');
delete from slice where name='my_slice';
commit;

Postgresql相关问答推荐

PostgreSQL:函数结果表内冲突(...)上的";中的字段名称

Jsonb[]字段中的PostgreSQL否定&q;-0.0

如何在Postgres中对分区表使用Hibernate验证?

无法使用PGx连接到Postgres数据库AWS RDS

PostGresql :正则表达式 Select 其中只有一个正斜杠的行

数据库所有者无法授予 Select 权限

使用 OpenCypher 和 Apache AGE 在两个顶点之间创建双向关系

找出两个表之间的差异

PG::UndefinedTable:错误:relation "active_storage_blobs" does not exist

Nodemon - 安装期间clean exit - waiting for changes before restart

如何从 postgresql Select 查询中的 age() 函数中仅获取年份

在 CentOS 上安装 psycopg2 时遇到问题

LAG 函数和 GROUP BY

如何查询存储在数组中的 Rails ActiveRecord 数据

返回 NULL 的空数组的 array_length()

如何确定 NULL 是否包含在 Postgres 的数组中?

在 postgres 中创建超级用户

Postgres Npgsql 连接池

docker postgres 无法从指定端口启动

如何在 PostgreSQL 中获取数组的最后一个元素?