"Foreign key constraint is incorrectly formed" Trying to make a old project work - mysql

So i'm trying to make a old project work again but when i put back my tables to the new database i'm having this issue
ERROR 1005 (HY000) at line 777: Can't create table ****.#sql-3f2_45 (errno: 150 "Foreign key constraint is incorrectly formed")
There is the table that causing problems:
CREATE TABLE `install__dashboards` (
`id` int(11) NOT NULL PRIMARY KEY,
`zone` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`protocol` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`agent` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`object` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`type` set('dashboard','visualization','search') DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Contraintes pour la table `install__dashboards`
--
ALTER TABLE `install__dashboards`
ADD CONSTRAINT `dash_agent` FOREIGN KEY (`agent`) REFERENCES `install__agents` (`name`),
ADD CONSTRAINT `dash_proto` FOREIGN KEY (`protocol`) REFERENCES `install__ports` (`protocol`),
ADD CONSTRAINT `dash_zone` FOREIGN KEY (`zone`) REFERENCES `install__zone` (`slug`);
References tables :
CREATE TABLE `install__agents` (
`id` int(11) NOT NULL,
`OS` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`zone` varchar(255) NOT NULL,
`IP` text,
`isLog` tinyint(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `install__ports` (
`id` int(11) NOT NULL,
`numero` int(11) NOT NULL,
`protocol` varchar(255) NOT NULL,
`isUDP` tinyint(1) NOT NULL DEFAULT '0',
`machine` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `install__zone` (
`slug` varchar(255) NOT NULL,
`status` enum('notpresent','installing','installed') NOT NULL,
`options` text,
`IPrange` text,
`IPsystem` text,
`system` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

To be honest, the error message isn't very descriptive :-(
To get more details about the cause of the error, just check InnoDB status:
$ mysql -e"SHOW ENGINE INNODB STATUS\G" | grep -C3 "FOREIGN KEY ERROR"
SEMAPHORES
----------
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2022-12-06 11:08:12 0x7f43a80ba700 Error in foreign key constraint of table `test`.`install__dashboards`:
Alter table `test`.`install__dashboards` with foreign key `dash_proto` constraint failed. There is no index in the referenced table where the referenced columns appear as the first columns.------------
So the problem/reason is There is no index in the referenced table where the referenced columns appear as the first columns

You need to create indexes on the referencing column:
CREATE INDEX `ix_install__agents_name` ON `install__agents` (`name`);
CREATE INDEX `ix_install__ports_protocol` ON `install__ports` (`protocol`);
CREATE INDEX `ix_install__zone_slug` ON `install__zone` (`slug`);
but your schema does not look right. It's better to have the ID of the entity.
Something like this:
CREATE TABLE `install__agents` (
`id` int(11) NOT NULL PRIMARY KEY,
`OS` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`zone` varchar(255) NOT NULL,
`IP` text,
`isLog` tinyint(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `install__ports` (
`id` int(11) NOT NULL PRIMARY KEY,
`numero` int(11) NOT NULL,
`protocol` varchar(255) NOT NULL,
`isUDP` tinyint(1) NOT NULL DEFAULT '0',
`machine` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `install__zone` (
`id` int(11) NOT NULL PRIMARY KEY,
`slug` varchar(255) NOT NULL,
`status` enum('notpresent','installing','installed') NOT NULL,
`options` text,
`IPrange` text,
`IPsystem` text,
`system` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `install__dashboards` (
`id` int(11) NOT NULL PRIMARY KEY,
`zone_id` int(11) DEFAULT NULL,
`protocol_id` int(11) DEFAULT NULL,
`agent_id` int(11)DEFAULT NULL,
`object` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`type` set('dashboard','visualization','search') DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `install__dashboards`
ADD CONSTRAINT `dash_agent` FOREIGN KEY (`agent_id`) REFERENCES `install__agents` (`id`),
ADD CONSTRAINT `dash_proto` FOREIGN KEY (`protocol_id`) REFERENCES `install__ports` (`id`),
ADD CONSTRAINT `dash_zone` FOREIGN KEY (`zone_id`) REFERENCES `install__zone` (`id`);

Related

Cannot add foreign key constraint

I have created a database "webportal". and this is my "user" table script
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`firstName` varchar(255) DEFAULT NULL,
`lastName` varchar(255) DEFAULT NULL,
`dateRegistered` DATE DEFAULT NULL,
`skypeID` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
and this one is "catalog" table script.
DROP TABLE IF EXISTS `catalog`;
create table catalog(
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`link` VARCHAR(100) NOT NULL,
`comment` VARCHAR(100) NOT NULL,
`inserDate` DATE DEFAULT NULL,
`content` longblob NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `fk_catalog` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and when I try to execute the second script in the command line, I get this error...
ERROR 1215 (HY000): Cannot add foreign key constraint.
What is wrong with this code?
It seems you are using a old version of MySQL, you can add a INDEX clause to foreign key field to fix the problem:
DROP TABLE IF EXISTS `catalog`;
create table `catalog`(
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`link` VARCHAR(100) NOT NULL,
`comment` VARCHAR(100) NOT NULL,
`inserDate` DATE DEFAULT NULL,
`content` longblob NOT NULL,
PRIMARY KEY (`id`),
INDEX (`user_id`),
CONSTRAINT `fk_catalog` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Mysql add foreign key constraint fails

I'm trying to add a foreign key constraint on my schema devair from field user_id of table bluePrints to the PK id of table users but I get an error:
ERROR 1215: Cannot add foreign key constraint
Here are my table definitions:
users:
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `users_email_unique` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
bluePrints:
CREATE TABLE `bluePrints` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`bluePrintName` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`description` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`user_id` int(10) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `uid` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
And the offending alter table statement:
ALTER TABLE `devair`.`bluePrints`
ADD CONSTRAINT `bp_u`
FOREIGN KEY (user_id)
REFERENCES `devair`.`users` (id)
ON DELETE CASCADE
ON UPDATE CASCADE;
The simple answer would be that you need to do this:
ALTER TABLE table1 ADD CONSTRAINT fk_bp_id FOREIGN KEY (columnFromTable1) REFERENCES table2(columnReferencedFromTable2);
The problem is the 'unsigned' in the bluePrints table. Once it's unsigned, then it works.
Now i have to figure out how to get laravel to use unsigned.

Foreign key constraint is incorrectly formed : MySQL

Session Table is here:
CREATE TABLE `sessions` (
`id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`user_id` int(11) DEFAULT NULL,
`ip_address` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
User Table is below
CREATE TABLE IF NOT EXISTS `tblusers` (
`UserID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`UserName` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`EmailAddress` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`RoleID` tinyint(4) NOT NULL,
PRIMARY KEY (`UserID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=17;
I tried below query to apply Foreign Key Constraint in Sessions Table
ALTER TABLE sessions
ADD CONSTRAINT FK_sessions_tblusers_UserID
FOREIGN KEY (user_id)
REFERENCES tblusers(UserID)
MySQL says
1005 - Can't create table myapp.#sql-6b8_83 (errno: 150 "Foreign
key constraint is incorrectly formed")
Question
Am I missing something ?
The issue here is that the column types of sessions.user_id and tblusers.UserID don't quite match. I reproduced the same error and fixed it by altering the two columns as follows...
`user_id` INT(11) UNSIGNED DEFAULT NULL
...and...
`UserID` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT
The foreign key was successfully created after I made those changes. Note that I didn't have to change the nullability to match, though you may want to do this with sessions.user_id if a session is required to have a user id...
`user_id` INT(11) UNSIGNED NOT NULL

Export localhost Sql and import it on Server gives me errno 150

I suggest something is wrong with the foreign keys, but i can't find a hint.
error while importing the sql:
ALTER TABLE `claim`
ADD CONSTRAINT `FK_66A8F1231B7B246A` FOREIGN KEY (`purchaseOrder_id`) REFERENCES `PurchaseOrder` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `FK_66A8F1237294869C` FOREIGN KEY (`article_id`) REFERENCES `Article` (`id`);
#1005 - Can't create table 'databasename.#sql-5c7_568c0' (errno: 150)
I also checked the conditions of this answer MySQL Creating tables with Foreign Keys giving errno: 150
But i couldn't find the mistake.
Any guesses?
Tables:
CREATE TABLE `Article` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`number` int(11) NOT NULL,
`currency` tinyint(1) NOT NULL,
`price` double NOT NULL,
`tolerance` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
CREATE TABLE `claim` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`comment` longtext COLLATE utf8_unicode_ci NOT NULL,
`purchaseOrder_id` int(11) DEFAULT NULL,
`visible` tinyint(1) NOT NULL,
`article_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_66A8F1231B7B246A` (`purchaseOrder_id`),
KEY `IDX_66A8F1237294869C` (`article_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `purchaseorder` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` datetime NOT NULL,
`state` int(11) NOT NULL,
`supplier_id` int(11) DEFAULT NULL,
`delivery_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_AA004F112ADD6D8C` (`supplier_id`),
KEY `IDX_AA004F1112136921` (`delivery_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Your table name is purchaseorder
--------------------------^-----------^
ALTER TABLE `claim`
ADD CONSTRAINT `FK_66A8F1231B7B246A` FOREIGN KEY (`purchaseOrder_id`) REFERENCES `purchaseorder` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `FK_66A8F1237294869C` FOREIGN KEY (`article_id`) REFERENCES `Article` (`id`);

Importing a database schema from a SQL DUMP

I have the following database schema that has a bunch of tables and foreign keys, when i try to import the sql dump i keep getting the following errors.
Can't create table errno 150
I understand that it is trying to create tables with dependencies of tables that are not created yet but i don't understand how to import the schema without butchering out all of the foreign keys and then re-creating them per the answers given on Stack and google.
There has to be an easier way, what do big companies do that have hundreds of tables?
I have the sql statements below and any suggestions would be appreciated. Thanks
#
# Encoding: Unicode (UTF-8)
#
DROP TABLE IF EXISTS `contact_interest`;
DROP TABLE IF EXISTS `contact_seeking`;
DROP TABLE IF EXISTS `interests`;
DROP TABLE IF EXISTS `job_current`;
DROP TABLE IF EXISTS `job_desired`;
DROP TABLE IF EXISTS `job_listings`;
DROP TABLE IF EXISTS `my_contacts`;
DROP TABLE IF EXISTS `profession`;
DROP TABLE IF EXISTS `seeking`;
DROP TABLE IF EXISTS `status`;
DROP TABLE IF EXISTS `zip_code`;
CREATE TABLE `contact_interest` (
`contact_id` int(10) unsigned NOT NULL,
`interest_id` int(10) unsigned NOT NULL,
KEY `mycontacts_contactinterest_fk` (`contact_id`),
KEY `interests_contactinterest_fk` (`interest_id`),
CONSTRAINT `mycontacts_contactinterest_fk` FOREIGN KEY (`contact_id`) REFERENCES `my_contacts` (`contact_id`),
CONSTRAINT `interests_contactinterest_fk` FOREIGN KEY (`interest_id`) REFERENCES `interests` (`interest_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `contact_seeking` (
`contact_id` int(10) unsigned NOT NULL,
`seeking_id` int(10) unsigned NOT NULL,
KEY `contactid_contactseeking_fk` (`contact_id`),
KEY `seeking_contactseeking_fk` (`seeking_id`),
CONSTRAINT `contactid_contactseeking_fk` FOREIGN KEY (`contact_id`) REFERENCES `my_contacts` (`contact_id`),
CONSTRAINT `seeking_contactseeking_fk` FOREIGN KEY (`seeking_id`) REFERENCES `seeking` (`seeking_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `interests` (
`interest_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`interest` varchar(50) DEFAULT NULL,
PRIMARY KEY (`interest_id`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=latin1;
CREATE TABLE `job_current` (
`contact_id` int(10) unsigned NOT NULL,
`title` varchar(20) DEFAULT NULL,
`salary` decimal(8,2) DEFAULT NULL,
`start_date` date DEFAULT NULL,
KEY `mycontacts_jobcurrent_fk` (`contact_id`),
CONSTRAINT `mycontacts_jobcurrent_fk` FOREIGN KEY (`contact_id`) REFERENCES `my_contacts` (`contact_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `job_desired` (
`contact_id` int(10) unsigned NOT NULL,
`title` varchar(20) DEFAULT NULL,
`salary_low` decimal(8,2) DEFAULT NULL,
`salary_high` decimal(8,2) DEFAULT NULL,
`available` date DEFAULT NULL,
`years_exp` int(11) DEFAULT NULL,
KEY `mycontacts_jobdesired_fk` (`contact_id`),
CONSTRAINT `mycontacts_jobdesired_fk` FOREIGN KEY (`contact_id`) REFERENCES `my_contacts` (`contact_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `job_listings` (
`job_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(25) DEFAULT NULL,
`salary` decimal(8,2) DEFAULT NULL,
`zip_code` char(5) DEFAULT NULL,
`description` varchar(50) DEFAULT NULL,
PRIMARY KEY (`job_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
CREATE TABLE `my_contacts` (
`contact_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`last_name` varchar(30) DEFAULT NULL,
`first_name` varchar(20) DEFAULT NULL,
`phone` char(10) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`birthday` date DEFAULT NULL,
`prof_id` int(11) unsigned NOT NULL,
`status_id` int(10) unsigned NOT NULL,
`zip_code` char(5) DEFAULT NULL,
PRIMARY KEY (`contact_id`),
KEY `profession_mycontacts_fk` (`prof_id`),
KEY `zipcode_mycontacts_fk` (`zip_code`),
KEY `status_my_contacts_fk` (`status_id`),
CONSTRAINT `profession_mycontacts_fk` FOREIGN KEY (`prof_id`) REFERENCES `profession` (`prof_id`),
CONSTRAINT `status_my_contacts_fk` FOREIGN KEY (`status_id`) REFERENCES `status` (`status_id`),
CONSTRAINT `zipcode_mycontacts_fk` FOREIGN KEY (`zip_code`) REFERENCES `zip_code` (`zip_code`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=latin1;
CREATE TABLE `profession` (
`prof_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`profession` varchar(30) DEFAULT NULL,
PRIMARY KEY (`prof_id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=latin1;
CREATE TABLE `seeking` (
`seeking_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`seeking` varchar(40) DEFAULT NULL,
PRIMARY KEY (`seeking_id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=latin1;
CREATE TABLE `status` (
`status_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`status` varchar(30) DEFAULT NULL,
PRIMARY KEY (`status_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
CREATE TABLE `zip_code` (
`zip_code` char(5) NOT NULL DEFAULT '',
`city` varchar(20) DEFAULT NULL,
`state` char(2) DEFAULT NULL,
PRIMARY KEY (`zip_code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I found that I only needed two lines to fix my issue, I added one 0 at the top and 1 at the bottom and I was good. Sorry to waste your time...
SET FOREIGN_KEY_CHECKS = 0;
SET FOREIGN_KEY_CHECKS = 1;
the easiest way would be to do it via commandline like this:
mysql db_name < backup-file.sql
this executes your sql file in one transaction. If you execute your stuff in one transaction then you won't get the foreign key errors.