PostgreSQL 约束

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3005226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 22:34:25  来源:igfitidea点击:

Postgresql constraint

postgresqlforeign-keys

提问by Ryan

I cannot seem to get this right, I am trying to modify a field to be a foreign key, with cascading delete... what am i doing wrong?

我似乎无法做到这一点,我正在尝试将字段修改为外键,并使用级联删除...我做错了什么?

ALTER TABLE my_table 
ADD CONSTRAINT  
FOREIGN KEY my_field 
REFERENCES my_foreign_table 
ON DELETE CASCADE;

回答by Magnus Hagander

It would help if you posted the error message. But I think you are just missing the parenthesis:

如果您发布错误消息会有所帮助。但我认为你只是缺少括号:

ALTER TABLE my_table 
ADD CONSTRAINT my_fk 
FOREIGN KEY (my_field) 
REFERENCES my_foreign_table 
ON DELETE CASCADE;

回答by Anonymous Coward

Just guessing: shouldn't you add a foreign key instead of a constraint?

只是猜测:您不应该添加外键而不是约束吗?

ALTER TABLE my_table ADD FOREIGN KEY (my_field) REFERENCES my_foreign_table;

Postgresql reference

PostgreSQL 参考

回答by Tregoreg

I'm still somehow missing here an answer with foreign column (foreign_field) explicitly specified:

我仍然不知何故在这里缺少foreign_field明确指定的外列 ( )的答案:

ALTER TABLE my_table
ADD CONSTRAINT my_fk
FOREIGN KEY (my_field)
REFERENCES my_foreign_table (foreign_field)
ON DELETE CASCADE;

回答by Gerardo Cortés Mendoza

This works to me, I add the column to the table and then add the constraint with references to the other table:

这对我有用,我将列添加到表中,然后将约束添加到另一个表的引用:

-- add column to table 
ALTER TABLE schema.table ADD COLUMN my_column type;  

-- add constraint to column 
ALTER TABLE schema.table ADD CONSTRAINT fk_name FOREIGN KEY (column)
REFERENCES schema.table (column) MATCH SIMPLE 
ON UPDATE NO ACTION ON DELETE NO ACTION;