sql - 如何在不删除子表的情况下删除 PostgreSQL 中的表

标签 sql postgresql postgresql-9.5

我有一个名为 Parent 的父表。 用作其他3个表child1,child2,child3的外键的父表id

我想删除表并重新创建父表。我不想丢失子表中的数据。

最佳答案

提醒,小心!

在使用之前,请确保在显式事务中尝试此操作,以检查该语句是否完全按照您希望的方式执行,仅此而已。您可以使用 BEGIN; 开始事务并使用 COMMIT; 保存它。如果出现任何问题,您始终可以使用 ROLLBACK;

手动回滚

相关文档:transactions


解决方案/1

使用 DROP TABLE ... CASCADE将删除表和依赖它的 ALL 对象( View ,外键约束......),在输出中将它们列为 NOTICE (至少在 psql 中) :

-- Replace table_name with the name of your parent table
DROP TABLE table_name CASCADE;

在这里引用手册,大胆强调我的:

(...) to drop a table that is referenced by a view or a foreign-key constraint of another table, CASCADE must be specified. (CASCADE will remove a dependent view entirely, but in the foreign-key case it will only remove the foreign-key constraint, not the other table entirely.)


解决方案/2

如果您更喜欢手动执行操作(当您不知道表的依赖范围时),请像往常一样删除您对子表的约束并删除父表。

通常,您会执行这些操作:

-- Replace object names to suit your case
-- Dropping foreign key constraint on child table pointing to parent table
ALTER TABLE child_table DROP CONSTRAINT constraint_name;
-- Repeat above for all constraints in all child tables
-- Drop the parent table
DROP TABLE parent_table;

相关文档:dropping constraint

关于sql - 如何在不删除子表的情况下删除 PostgreSQL 中的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52519614/

相关文章:

sql - 使用每个表函数的一列来比较两个表函数的结果

postgresql - 为什么 autovacuum 不吸尘我的 table ?

mysql - 从 MySQL 数据库中的数字中删除点和逗号

mysql - On 子句中的未知列(但确实存在)

sql - 如何自动将 View 列映射到其原始列以插入源表?

json - 如何将 to_jsonb 用作 row_to_jsonb?关于 "how much"的详细信息在哪里?

postgresql - Postgres JSONB 唯一约束

sql - Redshift 中选择查询的并发性

postgresql - 如何在 PostgreSQL 9.1.9 中显示大量 bool 值而不引起眼睛疲劳?

django - "graphite"用户身份认证失败