Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

errno: 150 "Foreign key constraint is incorrectly formed") MariaDB

Tags:

mysql

mariadb

When I run the following script:

 DROP TABLE IF EXISTS `schemaname`.`tablename` ;

 CREATE TABLE IF NOT EXISTS `schemaname`.`tablename` (
   `id` INT(11) NOT NULL AUTO_INCREMENT,
   `ip` VARCHAR(25) NOT NULL,
   `address` TEXT NULL DEFAULT NULL,
 PRIMARY KEY (`id`))
 ENGINE = InnoDB
 DEFAULT CHARACTER SET = latin1;

It returns these error:

Error Code: 1005. Can't create table `schemaname`.`tablename` (errno: 150 "Foreign key constraint is incorrectly formed")

There was a table with the same name but a different structured that I deleted and also I deleted the tables that had foreign key with it.

If I try to create it with another name, then it works. Why can't I create a table with the same name with that one that I deleted?

like image 721
Dr.Agos Avatar asked Dec 12 '14 16:12

Dr.Agos


People also ask

What is error no 150 in MySQL?

If these requirements are not satisfied, MySQL returns Error 1005 that refers to errno: 150 in the error message, which means that a foreign key constraint was not correctly formed. Altering a table returns an error (errno: 150) if a foreign key definition is incorrectly formed for the altered table.

How do I disable foreign key check?

You can disable foreign key check in MySQL by setting the system variable foreign_key_checks to 0. However, please note, after you enable foreign key checks, MySQL will not re-validate your existing data that you added after disabling foreign key check. It will only check any new additions/updates to your database.

What is set foreign_key_checks 0?

Setting foreign_key_checks to 0It affects data definition statements: DROP SCHEMA drops a schema even if it contains tables that have foreign keys that are referred to by tables outside the schema, and DROP TABLE drops tables that have foreign keys that are referred to by other tables.

Can a primary key be a foreign key?

The primary key column(s) can be used (along with the foreign key) to create a reference between two tables. As shown earlier, the primary key column of one table can be the foreign key column in another table. Thus, it creates a link between the two tables.


1 Answers

Find and remove the foreign key relation(s) between those tables you deleted.

It seems that MariaDB didn't do that automatically for you when you deleted the tables.

Find foreign key relations:

SELECT
  CONSTRAINT_NAME, 
  TABLE_NAME, 
  COLUMN_NAME, 
  REFERENCED_TABLE_NAME, 
  REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME = '<table>' OR TABLE_NAME = '<table>';

Drop relation:

DROP FOREIGN KEY <constraint_name>;
like image 172
Kaii Avatar answered Sep 27 '22 22:09

Kaii