创建外键约束时出现问题:MySQL

时间:2016-01-07 00:46:39

标签: php mysql

类别表

CREATE TABLE IF NOT EXISTS `tblcategory` (
  `CategoryID` int(11) NOT NULL AUTO_INCREMENT,
  `Category` varchar(25) NOT NULL,
  `IsActive` tinyint(1) NOT NULL,
  PRIMARY KEY (`CategoryID`),
  UNIQUE KEY `UK_tblcategory_Category` (`Category`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

子类别表

CREATE TABLE IF NOT EXISTS `tblsubcategory` (
  `SubCategoryID` int(11) NOT NULL AUTO_INCREMENT,
  `SubCategory` varchar(25) NOT NULL,
  `CategoryID` int(11) NOT NULL,
  `IsActive` int(11) NOT NULL,
  PRIMARY KEY (`SubCategoryID`),
  UNIQUE KEY `UK_tblSubCategory_SubCategory_CategoryID` (`CategoryID`,`SubCategory`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

以下是我试图在子Catgory表中添加外键引用的查询

ALTER TABLE tblsubcategory
ADD CONSTRAINT FK_tblsubcategory_tblcategory_CategoryID
FOREIGN KEY (CategoryID)
REFERENCES tblsubcategory(CategoryID)

MySQL说

  

1005 - 无法创建表myapp#sql-6b8_33(错误:150“外键约束形成错误”)

问题

我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

我认为您打算在其他表格中引用CategoryID ...

ALTER TABLE tblsubcategory
ADD CONSTRAINT FK_tblsubcategory_tblcategory_CategoryID
FOREIGN KEY (CategoryID)
REFERENCES tblcategory(CategoryID)

答案 1 :(得分:1)

您需要引用Category表,而不是SubCategory表:

ALTER TABLE tblsubcategory
ADD CONSTRAINT FK_tblsubcategory_tblcategory_CategoryID
FOREIGN KEY (CategoryID)
REFERENCES tblcategory(CategoryID)
           ^^^^^^^^^^^