我有一个名为 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/