简体   繁体   English

Postgresql:更改外键约束的操作

[英]Postgresql: Changing Action For Foreign Key Constraint

I have a simple table like below. 我有一个简单的表,如下所示。

create table chemlab.rule_header (
    id           serial PRIMARY KEY,
    name         varchar(50),
    grade        varchar(20),
    class_tag    varchar(20),    --tag added to sammple if match
    parent_id    int REFERENCES chemlab.rule_header(id) DEFAULT NULL,
    unique( grade, class_tag )
)

But afterwards, I found that I need to add ON DELETE action, the default is NO ACTION . 但之后,我发现我需要添加ON DELETE动作,默认为NO ACTION I couldn't figure out how to change the action. 我无法弄清楚如何改变行动。

Now I have to DROP & ADD 现在我必须DROPADD

ALTER table chemlab.rule_header 
    DROP CONSTRAINT rule_header_parent_id_fkey ;
ALTER TABLE rule_header  
    ADD CONSTRAINT rule_header_parent_id_fkey 
    FOREIGN KEY (parent_id) REFERENCES chemlab.rule_header(id) ON DELETE RESTRICT;

So what is the correct syntax to alter an action on foreign key constraint ? 那么改变外键约束操作的正确语法是什么?

Well, this not directly altering FOREIGN KEY constraint, and there are DROP and ADD still, though this is only one statement: 好吧,这不是直接改变FOREIGN KEY约束,而且还有DROPADD ,尽管这只是一个语句:

ALTER table  chemlab.rule_header 
    DROP CONSTRAINT rule_header_parent_id_fkey,
    ADD CONSTRAINT rule_header_parent_id_fkey 
    FOREIGN KEY (parent_id) REFERENCES chemlab.rule_header(id) ON DELETE RESTRICT;

Take a look at the documentation at https://www.postgresql.org/docs/current/sql-altertable.html . 请查看https://www.postgresql.org/docs/current/sql-altertable.html上的文档。 There are options to alter a few things about a constraint (like DEFERRABLE) but not for changing the action, as I understand you need. 有些选项可以改变关于约束的一些事情(比如DEFERRABLE),但不能改变动作,因为我理解你需要。

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

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