Good morning, I’m studing the SQL, and today I’ve found two ways of declaring a foreign key (for MySQL). I’d like to know what does it change between that two syntax and why should I need to set a name for the foreign key (Syntax 2).
Syntax 1:
CREATE TABLE `test2` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`idtest` int(10) unsigned NOT NULL,
`desc` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`idtest`) REFERENCES `test` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Syntax 2:
CREATE TABLE `test2` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`idtest` int(10) unsigned NOT NULL,
`desc` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_1` (`idtest`),
CONSTRAINT `FK_1` FOREIGN KEY (`idtest`) REFERENCES `test` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Thank you!
Functionally there is no difference.
The ability to name the Foreign Key yourself allows you to communicate to other developers what the key means, and conform to standard naming conventions, etc.