为什么这个外键失败了

时间:2015-07-06 21:34:15

标签: mysql foreign-keys heidisql

CREATE TABLE `fitness_pledges` (
    `ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `first_name` VARCHAR(250) NOT NULL,
    `last_name` VARCHAR(250) NOT NULL,
    `email` VARCHAR(100) NOT NULL,
    `token` BIGINT(20) UNSIGNED NOT NULL,
    `email_valid` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
    `entered_sweeps` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
    `referrals` INT(10) UNSIGNED NOT NULL DEFAULT '0',
    PRIMARY KEY (`ID`),
    UNIQUE INDEX `email` (`email`),
    UNIQUE INDEX `token` (`token`)
)
COMMENT='holds validation token, first name, last name, email address, number of referrals and whether sweepstakes was entered\r\n'
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;

CREATE TABLE `finess_referrals` (
    `ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `first_name` VARCHAR(250) NOT NULL,
    `last_name` VARCHAR(250) NOT NULL,
    `email` VARCHAR(100) NOT NULL,
    `token` BIGINT(20) UNSIGNED NOT NULL,
    `referral_token` BIGINT(20) UNSIGNED NOT NULL,
    `referral_validated` TINYINT(4) NOT NULL DEFAULT '0',
    PRIMARY KEY (`ID`),
    INDEX `token_FK` (`token`),
    INDEX `referral_token_FK` (`referral_token`),
    CONSTRAINT `referral_token_FK` FOREIGN KEY (`referral_token`) REFERENCES `fitness_pledges` (`token`) ON DELETE NO ACTION,
    CONSTRAINT `token_FK` FOREIGN KEY (`token`) REFERENCES `fitness_pledges` (`token`) ON DELETE NO ACTION
)
COMMENT='holds the first name, last name, email and validation token of the referrer as well as the token of the referred individual and a flag for whether the referred individual\'s email has been validated'
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;

由HeidiSQL生成的此Alter Table尝试为组合的first_name,last_name和email字段添加外键失败,并且外键约束未正确形成。字段都定义相同,排序相同。为什么会失败?

ALTER TABLE `finess_referrals`
ADD CONSTRAINT `first_last_email_FK` FOREIGN KEY (`first_name`, `last_name`, `email`) 
REFERENCES `fitness_pledges` (`first_name`, `last_name`, `email`) ON DELETE NO ACTION;

2 个答案:

答案 0 :(得分:1)

首先需要fitness_pledges (first_name, last_name, email)表中的索引。来自Using FOREIGN KEY Constraints

  

MySQL需要外键和引用键的索引,这样外键检查可以很快,不需要表扫描。

如果需要,它会自动在引用表中创建一个索引,但它对引用的表没有这样做。

所以你需要这样做:

CREATE INDEX first_last_email ON fitness_pledges (first_name, last_name, email);

答案 1 :(得分:0)

根据SQL标准,外键必须引用父表的主键或唯一键。如果主键具有多个列,则外键必须具有相同的列数和顺序