Foreign key constraint is incorrectly formed (MySQL) [closed]
-
08-03-2021 - |
Question
So, I have these two tables
CREATE TABLE IF NOT EXISTS `inart_ps_categories` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`inart_ps_category_id` int(11) UNSIGNED NOT NULL,
`parent_id` int(11) UNSIGNED DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`path` varchar(255) DEFAULT NULL,
`num_children` int(11) DEFAULT '0',
`flag` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;
CREATE TABLE IF NOT EXISTS `inart_ps_category_associations` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`inart_ps_category_id` int(11) UNSIGNED NOT NULL,
`categoryid` int(11) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (categoryid) REFERENCES `categories` (categoryid) ON DELETE CASCADE,
FOREIGN KEY (inart_ps_category_id) REFERENCES `inart_ps_categories` (inart_ps_category_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;
It outputs "Foreign key constraint is incorrectly formed" for no reason. The first Foreign key is correct and if I erase the second one, the query is executed. Can you see something wrong here?
Solution
Without seeing your categories table, your only problem is that the referenced columns like inart_ps_category_id
need an index, which you can achieve by using KEY(inart_ps_category_id)
:
CREATE TABLE IF NOT EXISTS `inart_ps_categories` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`inart_ps_category_id` int(11) UNSIGNED NOT NULL,
`parent_id` int(11) UNSIGNED DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`path` varchar(255) DEFAULT NULL,
`num_children` int(11) DEFAULT '0',
`flag` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY(`inart_ps_category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;
CREATE TABLE IF NOT EXISTS `inart_ps_category_associations` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`inart_ps_category_id` int(11) UNSIGNED NOT NULL,
`categoryid` int(11) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (categoryid) REFERENCES `categories` (categoryid) ON DELETE CASCADE,
FOREIGN KEY (inart_ps_category_id) REFERENCES `inart_ps_categories` (inart_ps_category_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;
OTHER TIPS
A Foreign Key should only reference the Primary Key of another table.
The one causing you difficulties does not.
CREATE TABLE inart_ps_categories
( id int(11) UNSIGNED NOT NULL AUTO_INCREMENT
, inart_ps_category_id int(11) UNSIGNED NOT NULL
. . .
, PRIMARY KEY ( id ) <-- Primary Key
)
CREATE TABLE inart_ps_category_associations
( id int(11) UNSIGNED NOT NULL AUTO_INCREMENT
, inart_ps_category_id int(11) UNSIGNED NOT NULL
. . .
, PRIMARY KEY ( id )
. . .
FOREIGN KEY ( inart_ps_category_id )
REFERENCES inart_ps_categories ( inart_ps_category_id ) <-- NOT Primary Key
)
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange