Postgresql constraint

2020-05-29 13:16发布

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 $4 
FOREIGN KEY my_field 
REFERENCES my_foreign_table 
ON DELETE CASCADE;

4条回答
Lonely孤独者°
2楼-- · 2020-05-29 13:27

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; 
查看更多
时光不老,我们不散
3楼-- · 2020-05-29 13:28

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

查看更多
一纸荒年 Trace。
4楼-- · 2020-05-29 13:41

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

ALTER TABLE my_table
ADD CONSTRAINT my_fk
FOREIGN KEY (my_field)
REFERENCES my_foreign_table (foreign_field)
ON DELETE CASCADE;
查看更多
地球回转人心会变
5楼-- · 2020-05-29 13:48

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;
查看更多
登录 后发表回答