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
;
This Alter Table, generated by HeidiSQL, attempting to add a Foreign Key for the combined first_name, last_name and email fields fails with Foreign key constraint is incorrectly formed. The fields are all defined the same, the collation is the same. Why is it failing?
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;
You need an index in the fitness_pledges
table for (first_name, last_name, email)
first. From Using FOREIGN KEY Constraints:
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan.
It will create an index in the referencing table automatically if necessary, but it doesn't do so for the referenced table.
So you need to do:
CREATE INDEX first_last_email ON fitness_pledges (first_name, last_name, email);