0

这是我创建三个表的架构。第三个具有以下两个的外键。我不知道为什么 MySQL 不能创建第三个。列的类型匹配。

DROP TABLE IF EXISTS `SET`;
CREATE TABLE IF NOT EXISTS `SET` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `SET_ID` int(11) DEFAULT 0,
  `SET_NAME` varchar(32) NOT NULL,
  `SET_RELEASE_DATE` date NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

DROP TABLE IF EXISTS `TYPE`;
CREATE TABLE IF NOT EXISTS `TYPE` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `TYPE_ID` int(11) DEFAULT 0,
  `TYPE_NAME` varchar(32) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

DROP TABLE IF EXISTS `CARD`;
CREATE TABLE IF NOT EXISTS `CARD` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `CARD_ID` int(11) NOT NULL DEFAULT 0,
  `CARD_NAME` varchar(64) DEFAULT NULL,
  `SET_ID` int(11) DEFAULT 0,
  `TYPE_1` int(11) DEFAULT 0,
  `TYPE_2` int(11) DEFAULT 0,
  `TYPE_3` int(11) DEFAULT 0,
  `TYPE_4` int(11) DEFAULT 0,
  PRIMARY KEY (`ID`),
  CONSTRAINT `card_idfk_1` FOREIGN KEY (`SET_ID`)
    REFERENCES `SET`(`SET_ID`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `card_t1fk_1` FOREIGN KEY (`TYPE_1`)
    REFERENCES `TYPE`(`TYPE_ID`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `card_t2fk_1` FOREIGN KEY (`TYPE_2`)
    REFERENCES `TYPE`(`TYPE_ID`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `card_t3fk_1` FOREIGN KEY (`TYPE_3`)
    REFERENCES `TYPE`(`TYPE_ID`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `card_t4fk_1` FOREIGN KEY (`TYPE_4`)
    REFERENCES `TYPE`(`TYPE_ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;
4

1 回答 1

1

当您创建外键关系时,相关键必须在引用表上有一个索引(请参见此处)。

例如,这段代码:

DROP TABLE IF EXISTS `SET`;
CREATE TABLE IF NOT EXISTS `SET` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `SET_ID` int(11) NOT NULL DEFAULT 0,
  `SET_NAME` varchar(32) NOT NULL,
  `SET_RELEASE_DATE` date NOT NULL,
  PRIMARY KEY (`ID`),
  index(set_id)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

修复card_idfk_1约束问题。注意:您可以使用keyindex作为关键字。

于 2013-05-26T01:27:06.863 回答