Mysql

外鍵約束格式不正確(MySQL)

  • October 14, 2020

所以,我有這兩張桌子

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;

它無緣無故地輸出“外鍵約束格式不正確”。第一個外鍵是正確的,如果我刪除第二個,則執行查詢。你能看出這裡有什麼不對嗎?

在沒有看到您的類別表的情況下,您唯一的問題是引用的列inart_ps_category_id需要一個索引,您可以使用以下方法來實現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;

引用自:https://dba.stackexchange.com/questions/276217