Executing SQL script in server ERROR: Error 1005: Can't create table (errno: 150)
-
16-06-2021 - |
Question
What could be the reason for this error?
CREATE TABLE IF NOT EXISTS `myhotel`.`roomer` (
`id` INT NOT NULL ,
`name` VARCHAR(45) NOT NULL ,
`start` DATE NOT NULL ,
`finish` DATE NOT NULL ,
`day` INT NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_id` (`id` ASC) ,
CONSTRAINT `fk_id`
FOREIGN KEY (`id` )
REFERENCES `myhotel`.`all_roomers` (`id_roomer` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `myhotel`.`all_roomers` (
`id_roomer` INT NOT NULL ,
`id_room` INT NOT NULL ,
`status` TINYINT(1) NOT NULL ,
INDEX `fk_id_room` (`id_room` ASC) ,
PRIMARY KEY (`id_roomer`, `id_room`) ,
CONSTRAINT `fk_id_room`
FOREIGN KEY (`id_room` )
REFERENCES `myhotel`.`room` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `myhotel`.`room` (
`id` INT NOT NULL AUTO_INCREMENT ,
`number` INT NOT NULL ,
`price` INT NOT NULL ,
`capacity` INT NOT NULL ,
`stars` INT NOT NULL ,
`status` TINYINT(1) NOT NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
The Error I get is : Executing SQL script in server
ERROR: Error 1005: Can't create table 'myhotel.roomer' (errno: 150)
Solution
According to the MySQL Docs (see here):
If MySQL reports an error number 1005 from a CREATE TABLE statement, and the error message refers to error 150, table creation failed because a foreign key constraint was not correctly formed.
I'd say from the looks of your script that it may be because the CREATE TABLE
statement you're using references the table myhotel.all_roomers
before it's created. I'd bet you need to create that table first before creating a foreign key reference to it.
Also, I'm not sure but it also looks as if you're using the id
column as both a primary key as well as a foriegn key. I'm not sure this is allowed either but can't find anywhere in the documentation that says it's incorrect.