如何添加“在删除级联”约束?


163

在PostgreSQL 8中,是否可以ON DELETE CASCADES在下表中添加两个外键而不删除后者?

# \d scores
        Table "public.scores"
 Column  |         Type          | Modifiers
---------+-----------------------+-----------
 id      | character varying(32) |
 gid     | integer               |
 money   | integer               | not null
 quit    | boolean               |
 last_ip | inet                  |
Foreign-key constraints:
   "scores_gid_fkey" FOREIGN KEY (gid) REFERENCES games(gid)
   "scores_id_fkey" FOREIGN KEY (id) REFERENCES users(id)

这两个引用的表都在下面-这里:

# \d games
                                     Table "public.games"
  Column  |            Type             |                        Modifiers
----------+-----------------------------+----------------------------------------------------------
 gid      | integer                     | not null default nextval('games_gid_seq'::regclass)
 rounds   | integer                     | not null
 finished | timestamp without time zone | default now()
Indexes:
    "games_pkey" PRIMARY KEY, btree (gid)
Referenced by:
    TABLE "scores" CONSTRAINT "scores_gid_fkey" FOREIGN KEY (gid) REFERENCES games(gid)

和这里:

# \d users
                Table "public.users"
   Column   |            Type             |   Modifiers
------------+-----------------------------+---------------
 id         | character varying(32)       | not null
 first_name | character varying(64)       |
 last_name  | character varying(64)       |
 female     | boolean                     |
 avatar     | character varying(128)      |
 city       | character varying(64)       |
 login      | timestamp without time zone | default now()
 last_ip    | inet                        |
 logout     | timestamp without time zone |
 vip        | timestamp without time zone |
 mail       | character varying(254)      |
Indexes:
    "users_pkey" PRIMARY KEY, btree (id)
Referenced by:
    TABLE "cards" CONSTRAINT "cards_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "catch" CONSTRAINT "catch_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "chat" CONSTRAINT "chat_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "game" CONSTRAINT "game_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "hand" CONSTRAINT "hand_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "luck" CONSTRAINT "luck_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "match" CONSTRAINT "match_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "misere" CONSTRAINT "misere_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "money" CONSTRAINT "money_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "pass" CONSTRAINT "pass_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "payment" CONSTRAINT "payment_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "rep" CONSTRAINT "rep_author_fkey" FOREIGN KEY (author) REFERENCES users(id)
    TABLE "rep" CONSTRAINT "rep_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "scores" CONSTRAINT "scores_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "status" CONSTRAINT "status_id_fkey" FOREIGN KEY (id) REFERENCES users(id)

而且我不知道在前面的表中添加2个索引是否有意义?

更新:谢谢,我在邮件列表中也得到了建议,我可以在1条语句中进行管理,因此无需显式启动事务:

ALTER TABLE public.scores
DROP CONSTRAINT scores_gid_fkey,
ADD CONSTRAINT scores_gid_fkey
   FOREIGN KEY (gid)
   REFERENCES games(gid)
   ON DELETE CASCADE;

1
有点过时,但是我注意到您尚未在引用列上创建索引(例如pref_scores.gid)。如果您在被引用的表上删除很多行,那么删除这些表将需要很长时间。一些数据库会在引用列上自动创建索引;PostgreSQL由您自己决定,因为在某些情况下它不值得。
kgrittn

1
谢谢!我实际上注意到删除操作要花很长时间,但不知道那是原因
Alexander Farber 2012年

1
当外键索引不值得使用时,会是哪种情况?
Alexander Farber 2012年

2
我把你的发现纳入了我的答案。(该声明也是一笔交易。)
Mike Sherrill'Cat Recall'

2
@AlexanderFarber:什么时候您想在FK的引用列上省略索引?当存在另一个不完全匹配的索引时,该匹配就足够好了(例如,对于频繁的相似性搜索,您可能会有一个trigram索引,对于FK删除也可以)。删除很少,可以安排在下班时间进行。当表具有引用值的频繁更新时。当引用表很小但经常更新时。异常经常发生,以至于PostgreSQL社区更喜欢对其进行控制而不是使其自动化。
kgrittn

Answers:


218

我敢肯定您不能简单地添加on delete cascade到现有的外键约束中。您必须先删除约束,然后添加正确的版本。在标准SQL中,我认为最简单的方法是

  • 开始交易,
  • 放下外键
  • 用添加外键on delete cascade,最后
  • 提交交易

对每个要更改的外键重复此操作。

但是PostgreSQL有一个非标准扩展名,使您可以在单个SQL语句中使用多个约束子句。例如

alter table public.scores
drop constraint scores_gid_fkey,
add constraint scores_gid_fkey
   foreign key (gid)
   references games(gid)
   on delete cascade;

如果您不知道要删除的外键约束的名称,则可以在pgAdminIII中查找它(只需单击表名称并查看DDL,或者展开层次结构,直到看到“约束”),或者您可以查询信息模式

select *
from information_schema.key_column_usage
where position_in_unique_constraint is not null

谢谢,这也是我的想法-但是如何使用外键?它们只是可以轻松删除和读取的约束(类似于NOT NULL)吗?
亚历山大·法伯

2
@AlexanderFarber:是的,它们被命名为约束,可以轻松添加和删除。但是您可能想在事务中执行此操作。更详细地更新了我的答案。
Mike Sherrill'Cat

+1用于在pgAdminIII中查找。它甚至为您提供了DROP CONSTRAINT和ADD CONSTRAINT命令,因此您只需将其复制并粘贴到查询窗口中,然后将命令编辑为所需的内容即可。
戴夫·皮尔

编写完查询后,我注意到我的Postgres GUI(Navicat)让我在GUI中进行以下更改:dl.dropboxusercontent.com/spa/quq37nq1583x0lf/wwqne-lw.png
danneu 2015年

对于大型表,是否可以NOT VALID在单独的事务中进行验证?我对此有未解决的问题
TheCloudlessSky

11

根据@Mike Sherrill Cat Recall的回答,这对我有用:

ALTER TABLE "Children"
DROP CONSTRAINT "Children_parentId_fkey",
ADD CONSTRAINT "Children_parentId_fkey"
  FOREIGN KEY ("parentId")
  REFERENCES "Parent"(id)
  ON DELETE CASCADE;

5

用法:

select replace_foreign_key('user_rates_posts', 'post_id', 'ON DELETE CASCADE');

功能:

CREATE OR REPLACE FUNCTION 
    replace_foreign_key(f_table VARCHAR, f_column VARCHAR, new_options VARCHAR) 
RETURNS VARCHAR
AS $$
DECLARE constraint_name varchar;
DECLARE reftable varchar;
DECLARE refcolumn varchar;
BEGIN

SELECT tc.constraint_name, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' 
   AND tc.table_name= f_table AND kcu.column_name= f_column
INTO constraint_name, reftable, refcolumn;

EXECUTE 'alter table ' || f_table || ' drop constraint ' || constraint_name || 
', ADD CONSTRAINT ' || constraint_name || ' FOREIGN KEY (' || f_column || ') ' ||
' REFERENCES ' || reftable || '(' || refcolumn || ') ' || new_options || ';';

RETURN 'Constraint replaced: ' || constraint_name || ' (' || f_table || '.' || f_column ||
 ' -> ' || reftable || '.' || refcolumn || '); New options: ' || new_options;

END;
$$ LANGUAGE plpgsql;

请注意:此函数不会复制初始外键的属性。它只需要外表名/列名,删除当前键并替换为新键。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.