Odd Cannot add foreign key constraint - mysql

I have an odd one. I cannot create a table using the following:
The table Users already exists in the DB, only UserTimeZones is to be added, and it fails.
CREATE TABLE `Users` (
`AccessFailedCount` int(11) NOT NULL,
`EmailConfirmed` bit(1) NOT NULL,
`Id` char(36) NOT NULL,
`NormalizedUserName` varchar(256) DEFAULT NULL,
`NormalizedEmail` varchar(256) DEFAULT NULL,
PRIMARY KEY (`Id`),
UNIQUE KEY `UserNameIndex` (`NormalizedUserName`),
KEY `EmailIndex` (`NormalizedEmail`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `UserTimeZones` (
`Id` char(36) NOT NULL,
`UserId` char(36) NOT NULL,
`TimeZoneOffsetInSeconds` int NOT NULL,
`LastUpdatedAt` datetime(6) NOT NULL,
CONSTRAINT `PK_UserTimeZones` PRIMARY KEY (`Id`),
CONSTRAINT `FK_UserTimeZones_Users_UserId` FOREIGN KEY (`UserId`) REFERENCES `Users` (`Id`) ON DELETE CASCADE
);
SHOW ENGINE INNODB STATUS;
Here is what the status shows:
------------------------ LATEST FOREIGN KEY ERROR
2018-11-09 11:26:44 0x7f832c523700 Error in foreign key constraint of
table fifty/UserTimeZones:
FOREIGN KEY (UserId) REFERENCES Users (Id) ON DELETE 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.
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.
Please refer to
http://dev.mysql.com/doc/refman/5.7/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
So I have the classic "Cannot add foreign key constraint".
What I have tried:
Placing the Users.Id column as first column : doesn't change anything
The column types are the same, the engines too...
Applying the migration without data in the DB -> it works
Running the script in a DB without data -> still doesn't work...
What is the problem?
Not sure it matters but I use entity framework core.

https://dev.mysql.com/doc/refman/8.0/en/innodb-foreign-key-constraints.html
Foreign key definitions for InnoDB tables are subject to the following
conditions:
InnoDB permits a foreign key to reference any index column or group of
columns. However, in the referenced table, there must be an index
where the referenced columns are listed as the first columns in the
same order.
But oddly the index seems to be needed on the referencing table:
https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html#foreign-keys-examples
So try adding an index on your table
CREATE TABLE `UserTimeZones` (
`Id` char(36) NOT NULL,
`UserId` char(36) NOT NULL,
`TimeZoneOffsetInSeconds` int NOT NULL,
`LastUpdatedAt` datetime(6) NOT NULL,
CONSTRAINT `PK_UserTimeZones` PRIMARY KEY (`Id`),
INDEX userid_ind (UserId),
CONSTRAINT `FK_UserTimeZones_Users_UserId` FOREIGN KEY (`UserId`) REFERENCES `Users` (`Id`) ON DELETE CASCADE
);
Note: this is what the error message says.

Related

Unable to create foreign key in database

I am trying to create a table with a varchar column as foreign key but MySQL gives me an error while creating the table. My query is like this:
CREATE TABLE `survey_hesco_subdivision` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`circle_code` VARCHAR(100) DEFAULT NULL,
`name` VARCHAR(100) DEFAULT NULL,
`circle_name` VARCHAR(100) DEFAULT NULL,
`division_code` VARCHAR(100) DEFAULT NULL,
`sub_div_code` VARCHAR(100) NOT NULL,
`division_name` VARCHAR(100) DEFAULT NULL,
PRIMARY KEY (`id`,`sub_div_code`),
KEY `id` (`id`)
) ENGINE=INNODB AUTO_INCREMENT=91 DEFAULT CHARSET=latin1;
The above table is already in used
Create table `accurate_mam`.`meter_ping`(
`id` int(11) NOT NULL AUTO_INCREMENT,
`meter_id` int(11) NOT NULL,
`meter_msn` varchar(100),
`sub_div_code` varchar(100) NOT NULL,
`sub_div_name` varchar(100),
primary key (`id`),
constraint `FK_PING_METER_ID` foreign key (`meter_id`) references
`accurate_mam`.`meters`(`id`) on delete Cascade,
constraint `FK_PIN_SUB_DIV` foreign key (`sub_div_code`) references
`accurate_mam`.`survey_hesco_subdivision`(`sub_div_code`) on delete Cascade
) ENGINE=InnoDB charset=latin1 collate=latin1_swedish_ci
The error I am getting is
Error Number : 1005
Error Message: Can't create table accurate_mam.meter_ping (errno: 150 "Foreign key constraint is incorrectly formed")
I have already looked into this question
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order.
InnoDB permits a foreign key to reference any index column or group of
columns. However, in the referenced table, there must be an index
where the referenced columns are listed as the first columns in the
same order.
So, just create a index like this, before creating child table :
CREATE INDEX `idx_survey_hesco_subdivision_sub_div_code` ON survey_hesco_subdivision(sub_div_code);
Although, It is not best practice to use non-unique column as reference columns in relationship. DELETE CASCADE will not behave properly in that case. I will suggest you create a unique key on sub_div_code of primary table as well.
For more details, refere to this
Source : Cannot add foreign key - StackOverflow
Have you already run CREATE TABLE meters? There error is caused by that table being missing. Let's see that CREATE.

Foreign key to a group of attributes given as primary key

I have a Class table with the primary keys as Section, Semester and Department. Another Student table with a USN as the primary key. First why does it allow me to reference Class.Semester from Student.SEM? Shouldn't I only be allowed to reference the primary key in Class from a group of attributes as foreign key in the Student? I also tried to reference Class.section from Student.Class and I get an error saying #1215 - Cannot add foreign key constraint.
CREATE TABLE `Class` (
`Semester` int(1) NOT NULL,
`Section` varchar(1) NOT NULL,
`Department` varchar(3) NOT NULL,
`CTID` varchar(10) NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `Class`
ADD PRIMARY KEY (`Semester`,`Section`,`Department`);
CREATE TABLE `student` (
`USN` varchar(10) NOT NULL,
`DOB` date DEFAULT NULL,
`Class` varchar(1) NOT NULL,
`SEM` int(1) NOT NULL,
`Dep` varchar(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;
ALTER TABLE `student`
ADD PRIMARY KEY (`USN`),
ADD KEY `Class` (`Class`,`SEM`,`Dep`),
ADD KEY `SEM` (`SEM`);
ALTER TABLE `student`
ADD CONSTRAINT `student_ibfk_1` FOREIGN KEY (`SEM`) REFERENCES `Class` (`Semester`) ON DELETE CASCADE ON UPDATE CASCADE;
MySQL supports a smaller number of columns from the available keys as long as the list of columns starts with the list of columns in the key, as described in 13.1.17.6 Using FOREIGN KEY Constraints:
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.
InnoDB permits a foreign key to reference any column or group of columns. However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.
So in your case you can use the column Semester because it's the start of your index (Semester, Section, Department), but you cannot use Section or Department.

Need help creating foreign keys sql error 1215

Hello my appologies for asking aid but i'm having a little issue in a database adding references
so i got a table
CREATE TABLE `kooien` (
`kooiid` INT(11) NOT NULL AUTO_INCREMENT,
`kooidlistppg` INT(11) NULL,
`quarantaine` BIT(1) NOT NULL,
`idvogelsoort` INT(11) NULL DEFAULT NULL,
`idvogelondersoort` INT(11) NULL DEFAULT NULL,
`vasteoflossekooie` BIT(1) NOT NULL,
`bezetofniet` BIT(1) NOT NULL,
`idlistsponsor` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`kooiid`),
INDEX `idvogelsoort` (`idvogelsoort`),
INDEX `idvogelondersoort` (`idvogelondersoort`),
INDEX `kooien_ibfk_4_idx` (`idlistsponsor`),
CONSTRAINT `kooien_ibfk_2` FOREIGN KEY (`idvogelsoort`) REFERENCES `vogelsoort` (`id`),
CONSTRAINT `kooien_ibfk_3` FOREIGN KEY (`idvogelondersoort`) REFERENCES `ondersoort` (`id`),
CONSTRAINT `kooien_ibfk_4` FOREIGN KEY (`idlistsponsor`) REFERENCES `personen` (`id`),
CONSTRAINT `FK_kooien_kooientoppg` FOREIGN KEY (`kooidlistppg`) REFERENCES `kooientoppg` (`id`))
COLLATE='utf8_general_ci'
ENGINE=InnoDB
Which appears like
kooiid|kooidlistppg|quarantaine|idvogelsoort|idvogelondersoort|Vasteoflossekooien|bezetofniet|lijstlist sponsor
Now my problem is making kooidlistppg references to kooidlistppg(id)
i do so with this query
ALTER TABLE `kooien`
DROP INDEX `FK_kooien_kooientoppg`,
ADD CONSTRAINT `FK_kooien_kooientoppg` FOREIGN KEY (`kooidlistppg`) REFERENCES `kooientoppg` (`id`);
/* SQL Fout (1215): Cannot add foreign key constraint */
ill add the create query for the table
CREATE TABLE `kooientoppg` (
`id` INT(11) NOT NULL,
`idpapegaaien` INT(11) NULL DEFAULT NULL
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
please know that its lack of a primary key is to convert a list to a mysql database
As explained in the MySQL manual, details of FOREIGN KEY errors with InnoDB can be checked with the following SQL command:
SHOW ENGINE INNODB STATUS
For example:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2017-01-22 23:43:46 0x7fc9fc0f1700 Error in foreign key constraint of table test/kooien:
FOREIGN KEY (`kooidlistppg`) REFERENCES `kooientoppg` (`id`))
COLLATE='utf8_general_ci'
ENGINE=InnoDB:
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.
Please refer to http://dev.mysql.com/doc/refman/8.0/en/innodb-foreign-key-constraints.html for correct foreign key definition.
As far as I can tell, adding an index to the referenced column would help:
ALTER TABLE kooientoppg ADD INDEX id_idx (id);

Cannot add foreign key constraint on mysql-workbench

I am trying to create a table through mysql workbench. I am getting the following error :-
Error 1215: Cannot add foreign key constraint SQL Statement:
CREATE TABLE `propman`.`imageadassociation` (
`ImageId` INT NOT NULL,
`AdId` INT NOT NULL,
INDEX `imageId_adassociation_idx` (`ImageId` ASC),
INDEX `adId_adassociation_idx` (`AdId` ASC),
CONSTRAINT `imageId_adassociation`
FOREIGN KEY (`ImageId`)
REFERENCES `propman`.`imagelocation` (`ImageId`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `adId_adassociation`
FOREIGN KEY (`AdId`)
REFERENCES `propman`.`advertisement` (`AdId`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
The imageLocation table create state statement is as follows :-
CREATE TABLE `imagelocation` (
`ImageId` int(11) NOT NULL,
`ImageLocationcol` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The advertisement tables create statement is as follows :-
CREATE TABLE `advertisement` (
`AdId` int(10) NOT NULL AUTO_INCREMENT,
`PropertyId` int(10) NOT NULL,
`AdTemplateId` int(10) NOT NULL,
`ValidFrom` date DEFAULT NULL,
`ValidTo` date DEFAULT NULL,
PRIMARY KEY (`AdId`),
KEY `AdTemplateId` (`AdTemplateId`),
CONSTRAINT `advertisement_ibfk_2` FOREIGN KEY (`AdTemplateId`) REFERENCES `adtemplate` (`AdTemplateId`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
imageadassociation is the referencing table. Tables imagelocation and advertisement are the referenced tables.
The 2 columns in the referenced need to satisfy the condition:
From the Mysql Manual page on Using Foreign Key Constraints:
Corresponding columns in the foreign key and the referenced key must
have similar data types. The size and sign of integer types must be
the same. The length of string types need not be the same. For
nonbinary (character) string columns, the character set and collation
must be the same.
and they need to have left-most indexes on them in the referenced tables. These conditions are not met.
In particular, there is no index on imageId
The display widths are not of importance (ie: int(11) )

Mysql Query Error #1005 150

I have a query but its showing error #1005 and 150 in details. Some innodb
How to get it right?
CREATE TABLE `iars` ( `id` int(10) unsigned NOT NULL auto_increment,
`SessionId` int(10) unsigned NOT NULL,
`TeacherId` int(10) unsigned NOT NULL,
`courseid` int(4) unsigned NOT NULL,
`semester` int(4) unsigned NOT NULL,
`PaperId` int(4) unsigned NOT NULL,
`groupid` int(4) unsigned NOT NULL,
`Type` varchar(4) default 1,
PRIMARY KEY (`id`),
UNIQUE KEY `Constrint_Index`
(`SessionId`,`TeacherId`,`courseid`,`semester`,`PaperId`,`groupid`),
KEY `FK_tid` (`TeacherId`),
KEY `FK_gid` (`GroupId`),
KEY `FK_pid` (`PaperId`),
CONSTRAINT `FK_gid` FOREIGN KEY (`GroupId`) REFERENCES `groups` (`id`) ON DELETE
CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_pid` FOREIGN KEY (`PaperId`) REFERENCES `papers` (`p_id`) ON DELETE
CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_ssessionid` FOREIGN KEY (`SessionId`) REFERENCES `sessions` (`id`) ON
DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_tid` FOREIGN KEY (`TeacherId`) REFERENCES `teachers` (`id`) ON DELETE
CASCADE ON UPDATE CASCADE )
From the MySQL manual:
You cannot issue DROP TABLE for an InnoDB table that is referenced by a FOREIGN KEY constraint, unless you do SET foreign_key_checks = 0. When you drop a table, the constraints that were defined in its create statement are also dropped.
If you re-create a table that was dropped, it must have a definition that conforms to the foreign key constraints referencing it. It must have the right column names and types, and it must have indexes on the referenced keys, as stated earlier. If these are not satisfied, MySQL returns error number 1005 and refers to error 150 in the error message.
This means one of your other tables is probably referencing a column in iars which you are not re-creating. The solution, then, is to weed through all of your tables (via describe queries) and see where the reference is and either add the referenced column to your CREATE TABLE here, or remove the reference, as appropriate for your schema.
edit a very helpful gem from later on that referenced page:
SHOW ENGINE INNODB STATUS;
reveals loads of good info on the foreign-key error which just occurred. It should point you exactly where you need to look.