简体   繁体   English

使用外键约束的表上的SQL DELETE查询非常慢

[英]Very slow SQL DELETE query on table with foreign key constraint

I have got some trouble with a SQL DELETE query. 我在使用SQL DELETE查询时遇到了一些麻烦。 I work on a database (postgres 9.3) with 2 tables (Parent and Child) . 我在一个带有2个表(父和子)的数据库(postgres 9.3)上工作。 The child has a relation to the parent with a foreign key. 孩子与父母有外键关系。

Parent Table 父表

CREATE TABLE parent
(
  id bigint NOT NULL,
  ...
  CONSTRAINT parent_pkey PRIMARY KEY (id)
)

Child Table 儿童表

CREATE TABLE child
(
  id bigint NOT NULL,
  parent_id bigint,
  ...
  CONSTRAINT child_pkey PRIMARY KEY (id),
  CONSTRAINT fk_adc9xan172ilseglcmi1hi0co FOREIGN KEY (parent_id)
      REFERENCES parent (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

I inserted in both tables 200'000 entries without any relation ( Child.parent_id = NULL) . 我在两个表中插入了200'000个没有任何关系的条目(Child.parent_id = NULL)

But a DELETE query like below has a duration of more than 20 minutes. 但是像下面这样的DELETE查询的持续时间超过20分钟。 And that even without a WHERE conditions. 即使没有WHERE条件也是如此。

DELETE FROM Parent;

If I don't add the relation constraints the execution time will be done in 400 ms. 如果我不添加关系约束,则执行时间将在400毫秒内完成。

What did I miss? 我错过了什么?

A workable solution is the example below. 一个可行的解决方案是下面的例子。 But I don't know if this is a good idea. 但我不知道这是不是一个好主意。 Maybe anyone could tell me a better way to do that. 也许有人可以告诉我一个更好的方法来做到这一点。

BEGIN WORK;
ALTER TABLE Parent DISABLE TRIGGER ALL;
DELETE FROM Parent;
ALTER TABLE Parent ENABLE TRIGGER ALL;
COMMIT WORK;

When you delete from Parent , the Child table needs to be queried by parent_id to ensure that no child row refers to the parent row you are about to delete. Parent删除时, parent_id需要查询Child表,以确保没有子行引用您要删除的父行。

To ensure that the child lookup runs quickly, you need to have an index on your parent_id column in the Child table. 要确保子查找快速运行,您需要在Child表中的parent_id列上有一个索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM