【发布时间】:2019-12-11 11:07:47
【问题描述】:
当在 postgresql 中删除父记录时,如何获取已删除的子记录?我有两个相关的表。外部表有一个具有on delete cascade 约束的外键。我想在删除父记录后保留子记录。
表格如下:
create table table1(
id int not null primary key
);
create table table2(
id int not null primary key,
table1id int not null,
foreign key(table1id) references table1(id) on delete cascade
);
假设表有记录。
table1
| id |
+----+
| 1 |
+----+
table2
| id | table1id |
+----+----------+
| 1 | 1 |
+----+----------+
所以我想在使用一条语句检索子记录后删除记录。
我试过DELETE FROM table1 WHERE EXISTS ( SELECT * FROM table2 WHERE id = 1) RETURNING *,但它只返回 table1 记录,而不是至少 table2 记录。 table2 删除的记录是我要在删除后使用的记录。如何实现?
【问题讨论】:
-
您是否意识到 table2 中可能有 other 记录,其中 table1id=1 ? (-->>
NOT EXISTS()) -
这是一对一的关系。
-
那你就不需要两张表了。
-
Table1 也与其他 2 个表相关。如果我将表合并为一个,它将失败 3NF,从而妨碍数据库的操作。
标签: postgresql subquery common-table-expression