Moein Hosseini
Moein Hosseini

Reputation: 4373

Can't create table in MySQL [error 150] when use foreign key

I have designed schema with MySQL workbench.

But it couldn't complete Database Synchronize.It can create tables with out foreign keys.

I copied SQL from MySQL WorkBench to execute in phpmysqadmin.

CREATE  TABLE IF NOT EXISTS `Books`.`Users` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`mail` VARCHAR(45) NOT NULL ,
`password` VARCHAR(45) NOT NULL ,
`smspassword` VARCHAR(8) NULL ,
`mobile` VARCHAR(16) NULL ,
`type` ENUM('admin','secretery','groupadmin','user') NOT NULL DEFAULT 'user' ,
`securelogin` ENUM('true','false') NULL DEFAULT 'true' ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `id_UNIQUE` (`id` ASC) ,
UNIQUE INDEX `mail_UNIQUE` (`mail` ASC) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci
COMMENT = 'Table to store users data'

Users table created successfully. But following table (Profile) can't be created.

CREATE  TABLE IF NOT EXISTS `Books`.`Profiles` (
`id` INT NOT NULL AUTO_INCREMENT ,
`firstname` VARCHAR(45) NOT NULL ,
`lastname` VARCHAR(45) NOT NULL ,
`title` VARCHAR(45) NOT NULL ,
`nationalcode` VARCHAR(45) NOT NULL ,
`User_id` INT NOT NULL ,
PRIMARY KEY (`id`, `User_id`) ,
INDEX `fk_Profiles_Users` (`User_id` ASC) ,
CONSTRAINT `fk_Profiles_Users`
FOREIGN KEY (`User_id` )
REFERENCES `Books`.`Users` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci

But it will be return:

#1005 - Can't create table 'Books.Profiles' (errno: 150)

Where is the problem, and how should I solve this?

Upvotes: 0

Views: 484

Answers (1)

Andreas Fester
Andreas Fester

Reputation: 36649

You need to match the primary id column type with the foreign key column type - your primary id in Users is UNSIGNED INT, but your foreign key in Profiles is INT. Try this:

CREATE TABLE IF NOT EXISTS `Books`.`Profiles` (
     `id` INT NOT NULL AUTO_INCREMENT ,
     `firstname` VARCHAR(45) NOT NULL ,
     `lastname` VARCHAR(45) NOT NULL ,
     `title` VARCHAR(45) NOT NULL ,
     `nationalcode` VARCHAR(45) NOT NULL ,
     `User_id` INT UNSIGNED NOT NULL ,          -- <<= Check the type here!
     PRIMARY KEY (`id`, `User_id`) ,
     INDEX `fk_Profiles_Users` (`User_id` ASC) ,
     CONSTRAINT `fk_Profiles_Users`
         FOREIGN KEY (`User_id` )
         REFERENCES `Books`.`Users` (`id` )
         ON DELETE CASCADE
         ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci;

Upvotes: 5

Related Questions