PostgreSQL删除所有内容

wljmcqd8  于 2022-10-15  发布在  PostgreSQL
关注(0)|答案(4)|浏览(212)

您好,我想删除我的PostgreSQL表中的所有数据,但不是表本身。我怎么能这么做?

at0kjp5o

at0kjp5o2#

可以通过多种方式删除PostgreSQL数据库中的一个或多个表的内容。

使用SQL删除表内容:

删除一张表的内容:

TRUNCATE table_name;
DELETE FROM table_name;

删除所有命名表的内容:

TRUNCATE table_a, table_b, …, table_z;

删除命名表和引用它们的表的内容(我将在本答案后面更详细地解释):

TRUNCATE table_a, table_b CASCADE;

使用pgAdmin删除表内容:

删除一张表的内容:

Right click on the table -> Truncate

删除表的内容和引用它的表:

Right click on the table -> Truncate Cascaded

删除和截断的区别:

从文档中:
DELETE从指定表中删除满足WHERE子句的行。如果没有WHERE子句,效果就是删除表中的所有行。http://www.postgresql.org/docs/9.3/static/sql-delete.html
Truncate是一个PostgreSQL扩展,它提供了一种更快的机制来从表中删除所有行。TRUNCATE可快速删除一组表中的所有行。它与对每个表的非限定删除具有相同的效果,但由于它实际上不扫描表,因此速度更快。此外,它可以立即回收磁盘空间,而不需要后续的真空操作。这在大型表格上最有用。http://www.postgresql.org/docs/9.1/static/sql-truncate.html

使用从其他表引用的表:

当您的数据库包含多个表时,这些表可能具有关系。例如,有三个表:

create table customers (
customer_id int not null,
name varchar(20),
surname varchar(30),
constraint pk_customer primary key (customer_id)
);

create table orders (
order_id int not null,
number int not null,
customer_id int not null,
constraint pk_order primary key (order_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);

create table loyalty_cards (
card_id int not null,
card_number varchar(10) not null,
customer_id int not null,
constraint pk_card primary key (card_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);

以及一些为这些表格准备的数据:

insert into customers values (1, 'John', 'Smith');

insert into orders values 
(10, 1000, 1),
(11, 1009, 1),
(12, 1010, 1);        

insert into loyalty_cards values (100, 'A123456789', 1);

表ORDERS引用表CUSTOMERS,表REALITY_CADES引用表CUSTOMERS。当您尝试截断/删除被其他表引用的表(另一个表具有对指定表的外键约束)时,会出现错误。要从所有三个表中删除内容,您必须为所有这些表命名(顺序并不重要)

TRUNCATE customers, loyalty_cards, orders;

或者只命名使用CASCADE关键字引用的表(您可以命名多个表,而不只是一个)

TRUNCATE customers CASCADE;

这同样适用于pgAdmin。右键单击Customers表,然后选择Truncate Cascaded。

zrfyljdw

zrfyljdw3#

对于表,DELETE通常速度更快,需要的锁定更少(对于并发加载很重要):

DELETE FROM tbl;

没有WHERE条件。
对于中等或更大的table,可以使用TRUNCATE,就像@Greg发布的那样:

TRUNCATE tbl;

很难确定“小”和“大”之间的界限,因为这取决于许多变量。您必须在您的安装中进行测试。

yfwxisqw

yfwxisqw4#

我为可能使用DBeaver工具的每个人找到了一种非常简单快捷的方法:只需选择要截断的所有表(SHIFT + clickCTRL + click),然后选择right click

如果您有外键,还可以在Settings面板上选择CASCADE选项。这就是它所需要的一切!

相关问题