当前位置: 首页 > 数据库 > 正文

postgresql truncate table

[摘要] 最近的Django项目使用了postgresql作为数据库,postgresql在使用上还是跟mysql有比较大区别,很多命令和语句都变了,操作方式也改变很大,今天在postgresql数据库上做一个简单的 postgresql truncate table 操作,由于涉及到了 ForeignKey CASCADE,会引发连锁反应,挺有趣。

我的表名:sudops_user_baseinfo
执行命令:

sql> TRUNCATE TABLE sudops_user_baseinfo;

因为有ForeignKey的关联表,会有如下报错,

输出:
ERROR:  cannot truncate a table referenced in a foreign key constraint
DETAIL:  Table "sudops_idc_info" references "sudops_user_baseinfo".
HINT:  Truncate table "sudops_idc_info" at the same time, or use TRUNCATE ... CASCADE.

SQL后面添加 CASCADE 再执行,可以 TRUNCATE 成功

sql> TRUNCATE TABLE sudops_user_baseinfo CASCADE;

这种方式是把数据多清掉了,但是自增的sequence仍然存在,TRUNCATE后重新插入数据库会接着sequence的自增ID开始,如图所示:

如果要同时 TRUNCATE 掉自增的 sequence,可以执行如下SQL语句:

sql> TRUNCATE TABLE sudops_user_baseinfo RESTART IDENTITY CASCADE;
输出:
NOTICE:  truncate cascades to table "sudops_idc_info"
NOTICE:  truncate cascades to table "sudops_server_baseinfo"
TRUNCATE TABLE

本文固定链接: https://sudops.com/postgresql-truncate-table.html | 运维速度

该日志由 u2 于2017年11月03日发表在 数据库 分类下,
原创文章转载请注明: postgresql truncate table | 运维速度
关键字: ,

报歉!评论已关闭.