Foreign key constraint is incorrectly formed : MySQL - 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

Related

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

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`);

Foreign key incorrectly formed error in MySQL in Manjaro Linux

"user table" is created successfully. Every columns and types is the same as "users table." But when I create an association table named "user_role," "user table" cannot be called. I only get this error in using MySQL with MariaDB. Installing mysql in windows and using like that is fine. Without changing that table name, is there anything I can do to make it right?
Two tables are dumped because I forget where did I put my original code. But I'll be the same.
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`email` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`course_id` bigint(20) DEFAULT NULL,
`password` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FKj8ce5cjkm11igsffixdxexrr9` (`course_id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`email` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`course_id` bigint(20) DEFAULT NULL,
`password` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `course_id` (`course_id`),
CONSTRAINT `users_ibfk_1` FOREIGN KEY (`course_id`) REFERENCES `course` (`id`) ON DELETE SET NULL) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`role_name` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
create table `user_role`(
`id` int auto_increment not null,
`user_id_fk` bigint,
`role_id_fk` int,
primary key (`id`),
foreign key (`user_id_fk`) references `user`(`id`),
foreign key (`role_id_fk`) references `role`(`id`)
);
--> references user(id) is not working but references users(id) is working. Is there any way to make it work? Or just change the name?
Suggest you don't have one table name being the plural of another (user vs users); it can lead to typos.
Don't use MyISAM for anything. (with rare exceptions)
If that is a many-to-many mapping table follow the tips in http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table
The foreign key is across tables defined with different engines(InnoDB and MyISAM):
create table `user_role`(
`id` int auto_increment not null,
`user_id_fk` bigint(20), -- matching data types
`role_id_fk` int(11) -- matching data types
,primary key (`id`)
,foreign key (`role_id_fk`) references `role`(`id`)
,foreign key (`user_id_fk`) references `user`(`id`)
);
db<>fiddle demo
Related: Why doesn't MySQL's MyISAM engine support Foreign keys?

Error 1215: Can't add foreign key constraint (InnoDB)

I'm struggling around to create a foreign key with the following query:
alter table `users` add constraint `users_sales_partner_id_foreign` foreign key (`sales_partner_id`) references `structures` (`sales_partner_id`) on update cascade
InnoDB log says, it can't match this index:
2017-02-27 10:25:47 Error in foreign key constraint of
table website_backend/users: foreign key
(sales_partner_id) references structures (sales_partner_id) on update cascade:
Cannot find an index in the referenced table where the referenced
columns appear as the first columns, or column types in the table and
the referenced table do not match for constraint.
I have already checked typos and data type incompatibility, but everything seems to be alright:
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`profile_id` int(10) unsigned NOT NULL,
`sales_partner_id` int(11) NOT NULL,
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`state` enum('pending','confirmed','active','deactivated') COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `users_profile_id_unique` (`profile_id`),
UNIQUE KEY `users_sales_partner_id_unique` (`sales_partner_id`),
UNIQUE KEY `users_email_unique` (`email`),
CONSTRAINT `users_profile_id_foreign` FOREIGN KEY (`profile_id`) REFERENCES `profiles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
CREATE TABLE `structures` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`sales_partner_id` int(11) NOT NULL,
`sales_partner_structure` int(11) DEFAULT NULL,
`active` tinyint(1) NOT NULL,
`blocked` tinyint(1) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
I can't get my problem, does somebody have a clue? Thanks in advance!
Thanks to Paul Spiegel for his reminding that I can only set FKs to the indexed fields. After another review I noticed that my referenced field was not indexed, that solved my problem.

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.

how to best design the DB in this situation

At a glance, the database schema looks like this:
The schema has to be in 3rd normal form (and I am aware that hotels.average_rating suggests otherwise, try to oversee that, since the database is not fully designed yet). This is for a tourist recommendation system.
The SQL:
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
CREATE TABLE `activities` (
`activity_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`activity_name` varchar(277) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`activity_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `bookings` (
`from_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`to_date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`belong_user` int(10) unsigned NOT NULL,
`belong_hotel` int(10) unsigned NOT NULL,
`rating` int(3) unsigned NOT NULL,
KEY `belong_user` (`belong_user`),
KEY `belong_hotel` (`belong_hotel`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `countries` (
`cuntry_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`country_name` varchar(20) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`cuntry_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `hotels` (
`hotel_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`hotel_name` varchar(128) COLLATE utf8_bin NOT NULL,
`hotel_stars` int(3) NOT NULL,
`hotel_description` text COLLATE utf8_bin NOT NULL,
`average_price` float unsigned NOT NULL,
`average_rating` float unsigned NOT NULL,
`total_rooms` int(10) unsigned NOT NULL,
`free_rooms` int(10) unsigned NOT NULL,
`belong_region` int(10) unsigned NOT NULL,
PRIMARY KEY (`hotel_id`),
KEY `belong_region` (`belong_region`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `hotels_activity_offers` (
`belong_hotel` int(10) unsigned NOT NULL,
`belong_activity` int(10) unsigned NOT NULL,
UNIQUE KEY `belong_hotel_2` (`belong_hotel`,`belong_activity`),
KEY `belong_hotel` (`belong_hotel`),
KEY `belong_activity` (`belong_activity`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `regions` (
`region_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`belong_country` int(10) unsigned NOT NULL,
`region_name` varchar(255) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`region_id`),
KEY `belong_country` (`belong_country`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `regions_activity_offers` (
`belong_region` int(10) unsigned NOT NULL,
`belong_activity` int(10) unsigned NOT NULL,
KEY `belong_region` (`belong_region`),
KEY `belong_activity` (`belong_activity`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `users` (
`user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(20) COLLATE utf8_bin NOT NULL,
`password` varchar(40) COLLATE utf8_bin NOT NULL COMMENT 'MD5',
`first_name` varchar(20) COLLATE utf8_bin NOT NULL,
`last_name` varchar(20) COLLATE utf8_bin NOT NULL,
`email` varchar(255) COLLATE utf8_bin NOT NULL,
`is_admin` tinyint(1) NOT NULL,
`is_active` tinyint(1) NOT NULL,
PRIMARY KEY (`user_id`),
KEY `is_active` (`is_active`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `users_favourite_activities` (
`belong_user` int(10) unsigned NOT NULL,
`belong_activity` int(10) unsigned NOT NULL,
UNIQUE KEY `belong_user_2` (`belong_user`,`belong_activity`),
KEY `belong_user` (`belong_user`),
KEY `belong_activity` (`belong_activity`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
ALTER TABLE `bookings`
ADD CONSTRAINT `bookings_ibfk_3` FOREIGN KEY (`belong_hotel`) REFERENCES `hotels` (`hotel_id`) ON DELETE CASCADE,
ADD CONSTRAINT `bookings_ibfk_2` FOREIGN KEY (`belong_user`) REFERENCES `users` (`user_id`) ON DELETE CASCADE;
ALTER TABLE `hotels`
ADD CONSTRAINT `hotels_ibfk_1` FOREIGN KEY (`belong_region`) REFERENCES `regions` (`region_id`) ON DELETE CASCADE;
ALTER TABLE `hotels_activity_offers`
ADD CONSTRAINT `hotels_activity_offers_ibfk_2` FOREIGN KEY (`belong_activity`) REFERENCES `activities` (`activity_id`) ON DELETE CASCADE,
ADD CONSTRAINT `hotels_activity_offers_ibfk_1` FOREIGN KEY (`belong_hotel`) REFERENCES `hotels` (`hotel_id`) ON DELETE CASCADE;
ALTER TABLE `regions`
ADD CONSTRAINT `regions_ibfk_1` FOREIGN KEY (`belong_country`) REFERENCES `countries` (`cuntry_id`) ON DELETE CASCADE;
ALTER TABLE `regions_activity_offers`
ADD CONSTRAINT `regions_activity_offers_ibfk_2` FOREIGN KEY (`belong_activity`) REFERENCES `activities` (`activity_id`) ON DELETE CASCADE,
ADD CONSTRAINT `regions_activity_offers_ibfk_1` FOREIGN KEY (`belong_region`) REFERENCES `regions` (`region_id`) ON DELETE CASCADE;
ALTER TABLE `users_favourite_activities`
ADD CONSTRAINT `users_favourite_activities_ibfk_1` FOREIGN KEY (`belong_user`) REFERENCES `users` (`user_id`) ON DELETE CASCADE,
ADD CONSTRAINT `users_favourite_activities_ibfk_2` FOREIGN KEY (`belong_activity`) REFERENCES `activities` (`activity_id`) ON DELETE CASCADE;
The question is: how to best add a "user activity log" feature which stores the activities a user has taken part to? Note that both regions and hotels can have activities, and I need to be able to tell whether that activity has taken place in a region or in a hotel. Referential integrity should be guaranteed.
Present a query (it should use JOIN shouldn't it?) which lists all users and their activities along with the hotel id or region id. (the one which is not applicable can be NULL if required).
Simple solutions are better - so preferably without stored procedures or anything which digs too much in mysql-specific features.
Your database is not normalized - and the way you've done it looks like a poster-child for why normalization is a good idea.
hotels.average_rating?
WTF?
While it can make sense to denormalize your data - this is not how to do it. Think about what you need to do when a user submits a hotel rating - you need to recalculate the value based on all the ratings submitted. If instead you held a sum_of_ratings (or even retained the current average) and a number of ratings then you could calculate the new values based on the hotel record and the new rating without having to look at the other ratings.