我们如何从两个表中引用? MySQL的

时间:2011-10-06 01:25:36

标签: mysql mysql-error-1064

这是我的表

CREATE TABLE IF NOT EXISTS `carslibrary` (
  `CarID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `CarName` varchar(255) NOT NULL,
  PRIMARY KEY (`CarID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;

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 ;

我想创建另一个参考CarID和ColorID

的表

我制作了一张名为facerecord的表

CREATE TABLE IF NOT EXISTS `facerecord` (
  `carslibrary_ID` int(10) NOT NULL,
  `colorslibrary_ID` int(11) NOT NULL,
  KEY `carslibrary_ID` (`carslibrary_ID`),
  KEY `colorslibrary_ID` (`colorslibrary_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

我收到此错误

Error creating foreign key on carslibrary_ID (check data types)

Error creating foreign key on colorslibrary_ID (check data types)

Error
ALTER TABLE  `facerecord` ADD FOREIGN KEY (  `carslibrary_ID` ) REFERENCES  `cars2`.`carslibrary` (
`CarID`
) ON DELETE SET NULL ON UPDATE SET NULL ;

ALTER TABLE  `facerecord` ADD FOREIGN KEY (  `colorslibrary_ID` ) REFERENCES  `cars2`.`colorslibrary` (
`ColorID`
) ON DELETE SET NULL ON UPDATE SET NULL ;

2 个答案:

答案 0 :(得分:2)

您的数据类型不匹配,因为主表使用unsigned整数类型,但您的facerecord表使用普通签名的INT(10), INT(11)作为数据类型。

facerecord更改为:

CREATE TABLE IF NOT EXISTS `facerecord` (
  `carslibrary_ID` int(10) unsigned NOT NULL,
  `colorslibrary_ID` int(11) unsigned NOT NULL,
  KEY `carslibrary_ID` (`carslibrary_ID`),
  KEY `colorslibrary_ID` (`colorslibrary_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

答案 1 :(得分:1)

CarIdColorId无符号整数,因此您应该使用:

CREATE TABLE IF NOT EXISTS `facerecord` (
  `carslibrary_ID` int(10) unsigned NOT NULL,
  `colorslibrary_ID` int(11) unsigned NOT NULL,
  KEY `carslibrary_ID` (`carslibrary_ID`),
  KEY `colorslibrary_ID` (`colorslibrary_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;