无法在MySQL中创建外键约束。错误号150

时间:2014-02-23 00:33:23

标签: mysql sql foreign-keys mysql-workbench

我正在尝试创建数据模型。它相当复杂,但我正在尝试将Splits表链接到Trials表。该模型的屏幕截图如下:

enter image description here

我正在尝试将Splits.protocol + Splits.resultID + Splits.trialNumber作为试验的外键。这三种关系是试验的主要关键。我正在使用MySQL Workbench执行此操作,它会抛出错误#150。有谁知道问题是什么?

以下是SQL语句及其在尝试执行时抛出的错误:

ERROR 1005: Can't create table '403898_BAMNormalized.#sql-7285_6c29081' (errno: 150)

SQL Statement:

ALTER TABLE `403898_BAMNormalized`.`Splits` 

ADD CONSTRAINT `FK_FromTrial`
    FOREIGN KEY (`protocol` , `resultID` , `trialNumber`)
    REFERENCES `403898_BAMNormalized`.`Trials` (`protocol` , `resultID` , `trialNumber`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION

ERROR: Error when running failback script. Details follow.

ERROR 1050: Table 'Splits' already exists

SQL Statement:

CREATE TABLE `Splits` (
    `protocol` varchar(255) NOT NULL,
    `resultID` int(11) NOT NULL,
    `trialNumber` int(11) NOT NULL,
    `splitNumber` int(11) NOT NULL,
    `splitScore` decimal(10,0) NOT NULL,
    PRIMARY KEY (`protocol`,`resultID`,`trialNumber`,`splitNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

以下是create table语句:

CREATE TABLE `Trials` (
    `resultID` int(11) NOT NULL,
    `protocol` varchar(255) NOT NULL,
    `trialNumber` int(11) NOT NULL,
    `trialScore` decimal(10,0) NOT NULL,
    `best` char(1) DEFAULT NULL,
    `DQFlag` varchar(45) DEFAULT NULL,
    PRIMARY KEY (`resultID`,`protocol`,`trialNumber`),
    CONSTRAINT `FK_trialID` FOREIGN KEY (`resultID`, `protocol`) REFERENCES `ResultsDetails` (`resultID`, `protocol`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `Splits` (
    `protocol` varchar(255) NOT NULL,
    `resultID` int(11) NOT NULL,
    `trialNumber` int(11) NOT NULL,
    `splitNumber` int(11) NOT NULL,
    `splitScore` decimal(10,0) NOT NULL,
    PRIMARY KEY (`protocol`,`resultID`,`trialNumber`,`splitNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

试验指数表:

enter image description here

1 个答案:

答案 0 :(得分:1)

重新排序索引以表示与外键相同的顺序是解决方案。有关详细信息,请参阅原始帖子附带的评论。