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) )
Related
I want to add composite foreign key to my MySQL Cluster table. When I try locally the statement is executed, but on cluster I get the following error:
Failed to add the foreign key constraint. Missing index for constraint... in the referenced table 'y'
This is the statement:
ALTER TABLE x
ADD CONSTRAINT fk_x_y
FOREIGN KEY (y_id, tenant_id)
REFERENCES y(id, tenant_id);
I have executed SHOW FULL COLUMNS FROM for both tables and both columns in each table are the same. Also I have index in y table on id, tenant_id.
MySQL Cluster version: 8.0.25-cluster
Edit 1:
SHOW CREATE TABLE results:
Table x:
CREATE TABLE `x` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`tenant_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_y_id_tenant_id` (`tenant_id`),
CONSTRAINT `fk_x_tenant_id` FOREIGN KEY (`tenant_id`) REFERENCES `tenant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=ndbcluster AUTO_INCREMENT=446 DEFAULT CHARSET=utf8;
Table y:
CREATE TABLE `reference_list` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`tenant_id` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `y_id_tenant_id` (`id`,`tenant_id`),
KEY `fk_y_id_tenant_id` (`tenant_id`),
CONSTRAINT `fk_y_id_tenant_id` FOREIGN KEY (`tenant_id`) REFERENCES `tenant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=ndbcluster AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
I am aware that tenant_id is DEFAULT NULL in one table and NOT_NULL in other, but changing both to DEFAULT NULL didn't solve the problem.
After running: SHOW WARNINGS; I found out I had to add UNIQUE index on id, tenant_id columns.
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.
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.
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.
I like to add foreign keys, this table, but not work! If I try new tables not work, but other, old tables it works. What's the problem?
CREATE TABLE `tanora` (
`idtanora` int(11) NOT NULL,
`tema` varchar(250) NULL,
`megjegyzes` varchar(255) DEFAULT NULL,
`datum` date NOT NULL,
`osztaly` varchar(20) NOT NULL,
`megtartott` int(11) NOT NULL,
`targy` varchar(45) NOT NULL,
`kezdete` time NOT NULL,
`vege` time NOT NULL,
PRIMARY KEY (`idtanora`),
UNIQUE KEY `idtanora_UNIQUE` (`idtanora`),
KEY `osztazon_idx` (`osztaly`)
) ENGINE=InnoDB DEFAULT CHARSET=latin2 COLLATE=latin2_hungarian_ci;
CREATE TABLE `osztaly` (
`osztalyazon` varchar(20) NOT NULL,
`osztalyfonokazon` varchar(11) NOT NULL,
`osztalynev` varchar(45) NOT NULL,
`indul` year(4) NOT NULL,
PRIMARY KEY (`osztalyazon`),
UNIQUE KEY `osztalyazon_UNIQUE` (`osztalyazon`),
KEY `ofazon_idx` (`osztalyfonokazon`),
CONSTRAINT `tanarazon01` FOREIGN KEY (`osztalyfonokazon`) REFERENCES `tanar` (`szemelyiszam`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin2 COLLATE=latin2_hungarian_ci;
ERROR 1215: Cannot add foreign key constraint
SQL Statement:
ALTER TABLE `enaplo`.`tanora`
ADD CONSTRAINT `osztalyra`
FOREIGN KEY (`osztaly`)
REFERENCES `enaplo`.`osztaly` (`osztalyazon`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
ERROR: Error when running failback script. Details follow.
ERROR 1050: Table 'tanora' already exists
SQL Statement:
CREATE TABLE `tanora` (
`idtanora` int(11) NOT NULL,
`tema` varchar(250) NOT NULL,
`megjegyzes` varchar(255) DEFAULT NULL,
`datum` date NOT NULL,
`osztaly` varchar(20) NOT NULL,
`megtartott` int(11) NOT NULL,
`targy` varchar(45) NOT NULL,
`kezdete` time NOT NULL,
`vege` time NOT NULL,
PRIMARY KEY (`idtanora`),
UNIQUE KEY `idtanora_UNIQUE` (`idtanora`)
) ENGINE=InnoDB DEFAULT CHARSET=latin2 COLLATE=latin2_hungarian_ci
foreign key (osztaly)
references enaplo.osztaly (osztalyazon)
on delete no action
on update no action:
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. See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Make sure that you have consistent column definitions:
In your referencing table osztaly the foreign key column osztalyfonokazon needs to be defined with the exact same characteristics as applied to the referenced field in the tanar table.
Currently, osztalyfonokazon in osztaly is defined as follows:
`osztalyfonokazon` VARCHAR(11) NOT NULL
So, then in the tanar table the szemelyiszam definition should look like either
`szemelyiszam` VARCHAR(11) PRIMARY KEY
or
`szemelyiszam` VARCHAR(11) UNIQUE KEY NOT NULL
Depends on your needs.
Either way, ensure that szemelyiszam is a PRIMARY KEY or at least a UNIQUE KEY that is declared NOT NULL in the referenced tanar table.
Additionally, MySQL requires that the referenced columns be indexed
for performance reasons. However, the system does not enforce a
requirement that the referenced columns be UNIQUE or be declared NOT
NULL. The handling of foreign key references to nonunique keys or keys
that contain NULL values is not well defined for operations such as
UPDATE or DELETE CASCADE. You are advised to use foreign keys that
reference only UNIQUE (including PRIMARY) and NOT NULL keys.
Source