0

create table我在 MySQL 中的语句有问题。

场景是,我想要一个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;
4

1 回答 1

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;
    
于 2012-09-15T13:18:23.633 回答