Craig Marker
Craig Marker

Reputation: 1

Error Code 1215. Cannot add foreign key constraint

Creating a new database here for school and having difficulty in understanding what's wrong here.

For example, I want to create this table (automated SQL output):

-- -----------------------------------------------------
-- Table `jobsearch`.`Employer`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `jobsearch`.`Employer` 
(
`EmployerID` SMALLINT(5) NOT NULL AUTO_INCREMENT,
`IndustryID` SMALLINT(5) NOT NULL,
`Address` VARCHAR(45) NOT NULL,
`City` VARCHAR(45) NOT NULL, 
`State` CHAR(2) NOT NULL,
`Zip` VARCHAR(5) NOT NULL,
`Phone` VARCHAR(10) NOT NULL,

PRIMARY KEY (`EmployerID`, `IndustryID`),
INDEX `fk_Employer_Industry1_idx` (`IndustryID` ASC),

CONSTRAINT `fk_Employer_Industry1`
    FOREIGN KEY (`IndustryID`) REFERENCES `job search`.`Industry` (`IndustryID`)

    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

I have this table that the foreign should be referencing (This table was created without any issue):

CREATE TABLE IF NOT EXISTS `jobsearch`.`Industry` 
(
`IndustryID` INT NOT NULL AUTO_INCREMENT,
`IndustryName` VARCHAR(45) NOT NULL,
`Region` VARCHAR(45) NOT NULL,

PRIMARY KEY (`IndustryID`))
ENGINE = InnoDB;

Upvotes: 0

Views: 291

Answers (1)

Darwin von Corax
Darwin von Corax

Reputation: 5246

The datatype for the referencing column must match exactly that of the referenced column. You've defined `Industry.IndustryID as

`IndustryID` INT ...

and Employer.IndustryID as

`IndustryID` SMALLINT(5) ...

Change Employer.IndustryID to INT and you should be shiny.

Upvotes: 1

Related Questions