MySQL Nullable FK和150错误

时间:2012-09-15 13:01:19

标签: mysql

我在MySQL中遇到create table语句问题。

方案是,我希望有一个表P_CDP存储一些信息,表P_CDPFiles存储上传文件的数据。

默认情况下,SelectedCDPFileID列应为NULL,除非用户选择了某个文件。然后该列由文件ID填充。但是,我仍然得到errno 150,为什么?我认为FK名称设置正确

CREATE TABLE `P_CDP` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `P_OrderID` int(11) NOT NULL DEFAULT '0',
  `SelectedCDPFileID` int(11) NULL,
  PRIMARY KEY (`ID`),
  KEY `FK_P_CDP_P_Orders` (`P_OrderID`),
  KEY `FK_P_CDP_P_CDPFiles` (`SelectedCDPFileID`),
  CONSTRAINT `FK_P_CDP_P_Orders` FOREIGN KEY (`P_OrderID`) REFERENCES `P_Orders` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `FK_P_CDP_P_CDPFiles` FOREIGN KEY (`SelectedCDPFileID`) REFERENCES `P_CDPFiles` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

CREATE TABLE `P_CDPFiles` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `FileID` int(11) NOT NULL DEFAULT '0',
  `P_CDPID` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`ID`),
  KEY `FK_P_CDPFiles_File` (`FileID`),
  KEY `FK_P_CDPFiles_P_CDP` (`P_CDPID`),
  CONSTRAINT `FK_P_CDPFiles_File` FOREIGN KEY (`FileID`) REFERENCES `File` (`FileID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `FK_P_CDPFiles_P_CDP` FOREIGN KEY (`P_CDPID`) REFERENCES `P_CDP` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

1 个答案:

答案 0 :(得分:2)

您正在尝试引用尚不存在的表。

如果你必须在这两个表之间的两个方向都有引用(通常表明设计很差),你将不得不:

  1. 创建第一个表而不引用尚未定义的表:

    CREATE TABLE `P_CDP` (
      `ID` int(11) NOT NULL AUTO_INCREMENT,
      `P_OrderID` int(11) NOT NULL DEFAULT '0',
      `SelectedCDPFileID` int(11) NULL,
      PRIMARY KEY (`ID`),
      KEY `FK_P_CDP_P_Orders` (`P_OrderID`),
      KEY `FK_P_CDP_P_CDPFiles` (`SelectedCDPFileID`),
      CONSTRAINT `FK_P_CDP_P_Orders` FOREIGN KEY (`P_OrderID`)
        REFERENCES `P_Orders` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
    ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
    
  2. 创建第二个表,包括对第一个表的引用:

    CREATE TABLE `P_CDPFiles` (
      `ID` int(11) NOT NULL AUTO_INCREMENT,
      `FileID` int(11) NOT NULL DEFAULT '0',
      `P_CDPID` int(11) NOT NULL DEFAULT '0',
      PRIMARY KEY (`ID`),
      KEY `FK_P_CDPFiles_File` (`FileID`),
      KEY `FK_P_CDPFiles_P_CDP` (`P_CDPID`),
      CONSTRAINT `FK_P_CDPFiles_File` FOREIGN KEY (`FileID`)
        REFERENCES `File` (`FileID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
      CONSTRAINT `FK_P_CDPFiles_P_CDP` FOREIGN KEY (`P_CDPID`)
        REFERENCES `P_CDP` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
    ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
    
  3. 更改第一个表以添加预期的约束:

    ALTER TABLE `P_CDP`
      ADD CONSTRAINT `FK_P_CDP_P_CDPFiles` FOREIGN KEY (`SelectedCDPFileID`)
      REFERENCES `P_CDPFiles` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION;