MySQL 5.5 add foreign key fails with errors [HY000][150] and [HY000][1005] - mysql

I have tried adding a foreign key like this...
ALTER TABLE OrderLineItem
ADD CONSTRAINT
FK_OrderLineItem_ShippingType_name FOREIGN KEY
(shippingType)
REFERENCES ShippingType(name);
Or like this in Mysql 5.5...
alter table OrderLineItem add foreign key
FK_OrderLineItem_ShippingType (shippingType) references ShippingType(name);
Every time I see the following error.
[2011-11-18 15:07:04] [HY000][150] Create table
'realtorprint_dev_dev/#sql-7d0_80' with foreign key constraint failed.
There is no index in the referenced table where the referenced columns
appear as the first columns.
[2011-11-18 15:07:04] [HY000][1005] Can't create table
'realtorprint_dev_dev.#sql-7d0_80' (errno: 150)
Both OrderLineItem.shippingType and ShippingType.name have a type of varchar(50) not null. ShippingType.name is the primaryKey of ShippingType.
Here is the result of show create table on ShippingType as well as OrderLineItem...
CREATE TABLE `shippingtype` (
`name` varchar(50) CHARACTER SET latin1 NOT NULL DEFAULT '',
`description` varchar(255) CHARACTER SET latin1 NOT NULL,
PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `orderlineitem` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`description` varchar(255) CHARACTER SET latin1 NOT NULL,
`lineNumber` int(11) NOT NULL,
`quantity` int(11) NOT NULL,
`quantityMultiplier` int(11) NOT NULL,
`unitPrice` decimal(10,2) NOT NULL,
`order_id` bigint(20) NOT NULL,
`productDefinition_id` bigint(20) NOT NULL,
`mlsId` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
`printProviderUnitCost` decimal(10,2) NOT NULL,
`shippingType` varchar(50) NOT NULL,
`address` varchar(255) DEFAULT NULL,
`zipPostal` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
`stateProvince` varchar(255) NOT NULL,
`country` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_OrderLineItem_productDefinition_id` (`productDefinition_id`),
KEY `idx_OrderLineItem_order_id` (`order_id`),
CONSTRAINT `FK_OrderLineItem_order_id` FOREIGN KEY (`order_id`) REFERENCES `userorder` (`id`),
CONSTRAINT `FK_OrderLineItem_productDefinition_id` FOREIGN KEY (`productDefinition_id`) REFERENCES `productdefinition` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10029 DEFAULT CHARSET=utf8;

It is possible is that Mysql gives this bad error when the column types do not match exactly - check collation / size etc.

orderLineItem.shippingType has character set utf8, but ShippingType.name has character set latin1. These are not compatible for the purposes of foreign key references.

Data type mismatches or PK not declared properly on referenced based tables.

Related

Getting cannot find an index in the referenced table error

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. Note that the internal storage type of ENUM and SET changed in tables created with >= InnoDB-4.1.12, and such columns in old tables cannot be referenced by such columns in new tables.
Above is the full description of error im getting. i checked the indexes of both table and should be fine but it still gives me this error.
Below is the tables structure.
CREATE TABLE `contact_address` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`address_type` int(5) DEFAULT NULL,
`address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`postcode` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`area` int(5) DEFAULT NULL,
`state` int(5) DEFAULT NULL,
`country` char(2) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`phone` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`fax` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`contact_branch_id` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` int(4) DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`updated_by` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_c_a_area` (`area`),
KEY `fk_c_a_state` (`state`),
KEY `fk_c_a_country` (`country`),
KEY `fk_c_a_contact_branch_id` (`contact_branch_id`),
KEY `fk_c_a_created_by` (`created_by`),
CONSTRAINT `fk_c_a_area` FOREIGN KEY (`area`) REFERENCES `ref_area` (`area_id`),
CONSTRAINT `fk_c_a_contact_branch_id` FOREIGN KEY (`contact_branch_id`) REFERENCES `contact_branch` (`id`),
CONSTRAINT `fk_c_a_created_by` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`),
CONSTRAINT `fk_c_a_state` FOREIGN KEY (`state`) REFERENCES `ref_state` (`state_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `ref_countries` (
`country_code` char(2) NOT NULL,
`country_id` int(11) NOT NULL AUTO_INCREMENT,
`country_name` varchar(80) NOT NULL,
`alpha_3` char(3) DEFAULT NULL,
`calling_code` int(5) NOT NULL,
`continent_name` varchar(30) DEFAULT NULL,
PRIMARY KEY (`country_code`),
KEY `country_id` (`country_id`)
) ENGINE=InnoDB AUTO_INCREMENT=253 DEFAULT CHARSET=utf8mb4;
Im trying to run this and giving me the error.
ALTER TABLE `contact_address`
ADD CONSTRAINT `fk_c_a_countries` FOREIGN KEY (`country`)
REFERENCES `ref_countries` (`country_code`);
The error message you're getting suggests that there's a problem with the foreign key constraint that you're trying to add to the contact_address table. Based on the table definitions you've provided, there are a couple of things that could be causing the issue:
The data type of the country column in the contact_address table is char(2), while the data type of the country_code column in the ref_countries table is char(2) NOT NULL. The NOT NULL constraint on the country_code column may be causing the problem.
Another possibility is that the ref_countries table have not have AUTO_INCREMENT on country_code column, but the contact_address table's country column is referencing that.
You can try the following:
Remove the NOT NULL constraint from the country_code column in the ref_countries table.
Add AUTO_INCREMENT to the country_code column in the ref_countries table.
Also, make sure that there is a matching value in the ref_countries table for each value of the country column in the contact_address table.

"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?

Updating a value using other tables in mySQL

I'm very new in MySQL and im making a school project. I have this table:
CREATE TABLE IF NOT EXISTS `Reserva` (
`idReservacion` int(10) NOT NULL AUTO_INCREMENT,
`importe` int(10) DEFAULT NULL,
`fecha` date DEFAULT NULL,
`idCliente` int(11) DEFAULT NULL,
PRIMARY KEY (`idReservacion`),
KEY `idCliente` (`idCliente`),
CONSTRAINT `Reserva_ibfk_1` FOREIGN KEY (`idCliente`) REFERENCES `Cliente` (`idcliente`)
) ENGINE=InnoDB AUTO_INCREMENT=60001 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
And im triying to make Importe a generated field by an update using the next tables
CREATE TABLE IF NOT EXISTS `PaseDeAbordar` (
`idPaseDeAbordar` int(11) NOT NULL AUTO_INCREMENT,
`hora` time DEFAULT NULL,
`idReservacion` int(5) NOT NULL,
`idAsiento` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
`idVuelo` int(11) NOT NULL,
`precioc` int(10) DEFAULT NULL,
PRIMARY KEY (`idPaseDeAbordar`),
KEY `idReservacion` (`idReservacion`),
KEY `idAsiento` (`idAsiento`),
KEY `idVuelo` (`idVuelo`),
CONSTRAINT `PaseDeAbordar_ibfk_1` FOREIGN KEY (`idVuelo`) REFERENCES `Vuelo` (`idvuelo`),
CONSTRAINT `PaseDeAbordar_ibfk_2` FOREIGN KEY (`idReservacion`) REFERENCES `Reservacion` (`idreservacion`),
CONSTRAINT `PaseDeAbordar_ibfk_3` FOREIGN KEY (`idAsiento`) REFERENCES `Asiento` (`idasiento`)
) ENGINE=InnoDB AUTO_INCREMENT=225001 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Pasedeabordar has the foreign keys from Vuelo and Asiento, this is the structure of those:
CREATE TABLE IF NOT EXISTS `Asiento` (
`idAsiento` varchar(5) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`idClase` int(11) NOT NULL,
`precio` int(11) NOT NULL,
PRIMARY KEY (`idAsiento`),
KEY `idClase` (`idClase`),
CONSTRAINT `Asiento_ibfk_1` FOREIGN KEY (`idClase`) REFERENCES `Clase` (`idclase`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Vuelo:
CREATE TABLE IF NOT EXISTS `Vuelo` (
`idVuelo` int(8) NOT NULL AUTO_INCREMENT,
`matriculaAvion` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`origen` varchar(4) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`destino` varchar(4) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`fechaVuelo` date NOT NULL,
`horaSalida` time NOT NULL,
`horaLlegada` time NOT NULL,
`duracion` time NOT NULL,
`tieneEscala` varchar(2) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT 'NO',
`precio` int(10) NOT NULL,
PRIMARY KEY (`idVuelo`),
KEY `origen` (`origen`),
KEY `destino` (`destino`),
KEY `matriculaAvion` (`matriculaAvion`),
CONSTRAINT `Vuelo_ibfk_1` FOREIGN KEY (`origen`) REFERENCES `Terminal` (`idterminal`),
CONSTRAINT `Vuelo_ibfk_2` FOREIGN KEY (`destino`) REFERENCES `Terminal` (`idterminal`),
CONSTRAINT `Vuelo_ibfk_3` FOREIGN KEY (`matriculaAvion`) REFERENCES `Avion` (`matricula`)
) ENGINE=InnoDB AUTO_INCREMENT=5501 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Importe is suposed to be generated on this way:
reservacion.importe=(precio from asiento+precio from vuelo) where paseabordar.reservacionid=importe.reservacionid
UPDATE reservacion r, pasedeabordar pa, vuelo v, asiento a
SET r.importe=SUM(v.precio+a.precio)
WHERE pa.idreservacion=r.idreservacion
AND pa.idAsiento=a.idAsiento
AND pa.idVuelo=v.idVuelo;
But this generates me an error
Error(1111): Invalid use of group function
Any ideas on what im doing wrong?
SUM() is a group function, which is used to add up cells from the same column. You are simply trying to add up two values from the same row.
r.importe=v.precio+a.precio should work.
By the way, it's considered good practice to join your tables explicitly, like this:
UPDATE reservacion r
JOIN pasedeabordar pa ON pa.idreservacion = r.idreservacion
JOIN vuelo v ON pa.idVuelo = v.idVuelo
JOIN asiento a ON pa.idAsiento = a.idAsiento
SET r.importe = v.precio + a.precio;

Error 1215 Cannot add foreign key constraint data types match

Not sure what else to check/do. I made sure the foreign key data type matches (char(36)) and I ensured the foreign key statement uses the correct syntax
Running this script i get error 1215
USE addm;
CREATE TABLE `addm`.`notificationResource` (
`notificationId` CHAR(36) NOT NULL ,
`resourceId` CHAR(36) NOT NULL ,
PRIMARY KEY (`notificationId`, `resourceId`) ,
INDEX `fk_notificationResource_notification_idx` (`notificationId` ASC) ,
INDEX `fk_notificationResource_resource_idx` (`resourceId` ASC) ,
CONSTRAINT `fk_notificationResource_notification`
FOREIGN KEY (`notificationId` )
REFERENCES `addm`.`notification` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_notificationResource_resource`
FOREIGN KEY (`resourceId` )
REFERENCES `addm`.`resource` (`resourceId` )
ON DELETE NO ACTION
ON UPDATE NO ACTION);
commit;
Parent Tables:
CREATE TABLE `resource` (
`resourceId` char(36) NOT NULL,
`resourceName` varchar(255) DEFAULT NULL,
`resourceData` longblob,
PRIMARY KEY (`resourceId`),
UNIQUE KEY `resourceName_UNIQUE` (`resourceName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$
CREATE TABLE `notification` (
`notificationType` varchar(5) CHARACTER SET latin1 NOT NULL,
`id` char(36) CHARACTER SET latin1 NOT NULL,
`aborted` bit(1) DEFAULT NULL,
`attempts` int(11) DEFAULT NULL,
`content` longblob,
`recordDate` datetime DEFAULT NULL,
`sent` bit(1) DEFAULT NULL,
`sentDate` datetime DEFAULT NULL,
`subject` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
`fromUser_id` bigint(20) DEFAULT NULL,
`toUser_id` bigint(20) DEFAULT NULL,
`attachmentName` varchar(100) CHARACTER SET latin1 DEFAULT NULL,
`attachmentData` longblob,
`category` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
`read` tinyint(1) DEFAULT '0',
`locked` tinyint(1) DEFAULT '0',
PRIMARY KEY (`id`),
KEY `FK2D45DD0B7F734EAD` (`toUser_id`),
KEY `FK2D45DD0BE62E629E` (`fromUser_id`),
CONSTRAINT `FK2D45DD0B7F734EAD` FOREIGN KEY (`toUser_id`) REFERENCES `user` (`id`),
CONSTRAINT `FK2D45DD0BE62E629E` FOREIGN KEY (`fromUser_id`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$
I think column CHARACTER SET is different. id char(36) CHARACTER SET latin1 NOT NULL
change CHARACTER SET