Error 1215 Cannot add foreign key constraint data types match - mysql

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

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

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;

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.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row on CONSTRAINT `fk_users_has_ratings_businesses1

I'm getting this error when i try to insert new ratings
Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`yuldi`.`users_ratings`, CONSTRAINT `fk_users_has_ratings_businesses1` FOREIGN KEY (`business_id`) REFERENCES `businesses` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
below database table structure with some foreign keys. i'm confused with adding multiple primary and foreign keys. please help me to sort out this issue
CREATE TABLE IF NOT EXISTS `yuldi`.`businesses` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`state` VARCHAR(100) NOT NULL,
`slug` VARCHAR(250) NOT NULL,
`city` VARCHAR(100) NOT NULL,
`suburb` VARCHAR(100) NOT NULL,
`business_name` VARCHAR(100) NOT NULL,
`business_address` VARCHAR(250) NOT NULL,
`business_postal` VARCHAR(10) NOT NULL,
`business_postal_id` INT(11) NOT NULL,
`business_phone` VARCHAR(50) NOT NULL,
`business_phone1` VARCHAR(50) NOT NULL,
`business_phone2` VARCHAR(50) NOT NULL,
`business_email` VARCHAR(100) NOT NULL,
`business_website` VARCHAR(200) NOT NULL,
`business_details` VARCHAR(5000) NOT NULL,
`business_openinghours` VARCHAR(200) NOT NULL,
`business_service` VARCHAR(200) NOT NULL,
`business_addtionalinfo` VARCHAR(200) NOT NULL,
`business_lat` FLOAT(10,6) NOT NULL,
`business_lng` FLOAT(10,6) NOT NULL,
`identity` VARCHAR(100) NOT NULL,
`status` INT(11) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 232
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`ratings` (
`id` VARCHAR(36) NOT NULL,
`model` VARCHAR(255) NOT NULL,
`value` FLOAT(8,4) NULL DEFAULT '0.0000',
`comment` TEXT NULL DEFAULT NULL,
`created` DATETIME NULL DEFAULT NULL,
`modified` DATETIME NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `UNIQUE_RATING` (`model` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_email` VARCHAR(255) NULL DEFAULT NULL,
`user_password` CHAR(100) NULL DEFAULT NULL,
`user_name` VARCHAR(255) NULL DEFAULT NULL,
`user_code` VARCHAR(255) NULL DEFAULT NULL,
`user_status` TINYINT(4) NULL DEFAULT '0',
`created` DATETIME NULL DEFAULT NULL,
`modified` DATETIME NULL DEFAULT NULL,
`ip_address` VARCHAR(15) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 14
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`users_ratings` (
`user_id` INT(11) NOT NULL,
`rating_id` VARCHAR(36) NOT NULL,
`business_id` INT(11) NOT NULL,
PRIMARY KEY (`user_id`, `rating_id`, `business_id`),
INDEX `fk_users_has_ratings_ratings1_idx` (`rating_id` ASC),
INDEX `fk_users_has_ratings_users1_idx` (`user_id` ASC),
INDEX `fk_users_has_ratings_businesses1_idx` (`business_id` ASC),
CONSTRAINT `fk_users_has_ratings_businesses1`
FOREIGN KEY (`business_id`)
REFERENCES `yuldi`.`businesses` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_users_has_ratings_ratings1`
FOREIGN KEY (`rating_id`)
REFERENCES `yuldi`.`ratings` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_users_has_ratings_users1`
FOREIGN KEY (`user_id`)
REFERENCES `yuldi`.`users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
The problem is coming from this:
CONSTRAINT `fk_users_has_ratings_businesses1`
FOREIGN KEY (`business_id`)
REFERENCES `yuldi`.`businesses` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
The record you're trying to insert / update - probably user_ratings - is foreign keyed to the businesses table; you can't create a user_ratings record without a business_id, and that business_id must actually exist as an id in the businesses table.

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

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.