這裏有我的兩個表MySQL不能建立外鍵
CREATE TABLE IF NOT EXISTS `carslibrary` (
`CarID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`CarName` varchar(255) NOT NULL,
`colorslibrary_ID` int(11) unsigned NOT NULL,
PRIMARY KEY (`CarID`),
KEY `colorslibrary_ID` (`colorslibrary_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
CREATE TABLE IF NOT EXISTS `colorslibrary` (
`ColorID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`ColorName` varchar(255) NOT NULL,
PRIMARY KEY (`ColorID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
我得到下面的查詢時出現錯誤:
ALTER TABLE `carslibrary` ADD FOREIGN KEY ( `colorslibrary_ID`)
REFERENCES `cars2`.`colorslibrary` (`ColorID`);
MySQL的說:
#1452 - 不能添加或更新子行:外鍵約束 失敗(`cars2`。<結果2時解釋文件名 '#SQL-cf8_41a' >,約束`#SQL-cf8_41a_ibfk_1` FOREIGN KEY (`colorslibrary_ID`)參考`colorslibrary`(`ColorID`))
這可能是危險的,因爲它表明汽車引用缺失的顏色。 –