2

I'm trying to add a self-referencing FOREIGN KEY CONSTRAINT on a table (comment):

SET
FOREIGN_KEY_CHECKS = OFF;

ALTER TABLE
`comment` ADD CONSTRAINT comment_parent_id_foreign FOREIGN KEY(parent_id) REFERENCES `comment`(id) ON DELETE CASCADE;

And I get this error:

#1825 - Failed to add the foreign key constraint on table 'comment'. Incorrect options in FOREIGN KEY constraint 'databasename/comment_parent_id_foreign'

Earlier I accidentally added this constraint on an unintended table (post). I wasn't able to delete the constraint, so I removed the column (parent_id) itself. I created this column again. And now I'm not able to add this self-referencing constraint.

Both have same datatype bigint(20) (id and parent_id) and commentid is a primary key

Table is using InnoDB engine

Here's my table structure:

enter image description here

thanks

Sumit Wadhwa
  • 2,825
  • 1
  • 20
  • 34

5 Answers5

2

1.Engine should be the same e.g. InnoDB

2.Datatype should be the same, and with same length. e.g. VARCHAR(50)

3.Collation Columns charset should be the same. e.g. utf-8

4.Unique - Foreign key should refer to field that is unique in the reference table

5.Nullable If the constraint's action is SET NULL, make sure that the column is nullable.

stollr
  • 6,534
  • 4
  • 43
  • 59
Ramki
  • 452
  • 2
  • 16
2

' The size and sign of integer types must be the same' - dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html - change so that both are unsigned.

P.Salmon
  • 17,104
  • 2
  • 12
  • 19
1

For those coming from Google: If you have this in your query, ensure that the column is nullable.

ON DELETE SET NULL
John Muraguri
  • 426
  • 7
  • 6
0

Try this :

ALTER TABLE comment ADD CONSTRAINT fk_comment_parent_id FOREIGN KEY (parent_id) REFERENCES comment(id);
Ramki
  • 452
  • 2
  • 16
0

If you do not find the reason for the error, try this to get more details about the error:

SHOW ENGINE INNODB STATUS

And in the output search for LATEST FOREIGN KEY ERROR.

Credits go to @sidonai.

stollr
  • 6,534
  • 4
  • 43
  • 59