Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign key constraint is incorrectly formed?

Tags:

mysql

I got this errore when create table: Foreign key constraint is incorrectly formed???

{create table comment(
Comment_ID int UNSIGNED AUTO_INCREMENT not null,
User_1 varchar(50) not null,
Note_ID int(11) UNSIGNED not null,
PRIMARY key(Comment_ID),
  CONSTRAINT `fk_1` FOREIGN KEY (`User_1`) REFERENCES `user` (`Dev_ID`),
  CONSTRAINT `fk_2` FOREIGN KEY (`User_2`) REFERENCES `user` (`Dev_ID`),
  CONSTRAINT `fk_3` FOREIGN KEY (`Note_ID`) REFERENCES `note`(`Note_ID`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
}

it's ok when i remove fk_3
this my note table

{ 
CREATE TABLE `note` (
 `Dev_ID` varchar(50) NOT NULL,
  `Note_ID` int(11) UNSIGNED NOT NULL,
  `Title` varchar(200) NOT NULL,
  `Time` datetime NOT NULL,
  `Mood` int(11) NOT NULL,
  `Body` varchar(3000) NOT NULL,
  `Visible` tinyint(1) NOT NULL DEFAULT '1',
  `Share` tinyint(1) NOT NULL DEFAULT '0',
  `Update` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`Dev_ID`,`Note_ID`),
  CONSTRAINT `fk_note_user` FOREIGN KEY (`Dev_ID`) REFERENCES `user` (`Dev_ID`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8
}

Thanks for help!

like image 985
user1235872 Avatar asked Apr 09 '12 18:04

user1235872


2 Answers

That's because the primary key of the notes table is (Dev_ID,Note_ID) but you are only referencing one of those columns (Note_ID) in your constraint.

A FK constraint must always consist of all PK columns.

like image 124
a_horse_with_no_name Avatar answered Sep 19 '22 15:09

a_horse_with_no_name


Also make sure that both tables are innoDB.

like image 44
Handsome Nerd Avatar answered Sep 20 '22 15:09

Handsome Nerd