duplicate key in table for foreign key in sql - mysql

I am using mysql_workbench to create database I have products_types, categories and subcategories table. category_id and subcategory_id are the foreign keys referencing to categories and subcategories table respectively. When when I forward engineer this model from workbench to mysql database on phpMyAdmin it gives error as
Can't write; duplicate key in table 'product_types'
This is the exact code along with error.
Executing SQL script in server
ERROR: Error 1022: Can't write; duplicate key in table 'product_types'
SQL Code:
-- -----------------------------------------------------
-- Table `argo_project_01_2`.`product_types`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `argo_project_01_2`.`product_types` (
`id` INT NOT NULL,
`category_id` INT NULL,
`subcategory_id` INT NULL,
`title` VARCHAR(100) NULL,
`description` TEXT NULL,
`status` INT NULL DEFAULT 0,
`created` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
`modified` TIMESTAMP NULL,
PRIMARY KEY (`id`),
INDEX `category_id_idx` (`category_id` ASC),
INDEX `subcategory_id_idx` (`subcategory_id` ASC),
CONSTRAINT `category_id`
FOREIGN KEY (`category_id`)
REFERENCES `argo_project_01_2`.`categories` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `subcategory_id`
FOREIGN KEY (`subcategory_id`)
REFERENCES `argo_project_01_2`.`subcategories` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
SQL script execution finished: statements: 9 succeeded, 1 failed
Fetching back view definitions in final form.
Nothing to fetch
What is wrong in the query ?

I think the problem may be solved by Changing constraint names "category_id" and "subcategory_id" to for example "fk_category_id" and "fk_subcategory_id".
Edit :
Also you can remove "category_id_idx" and "subcategory_id_idx" indexes because the foreign key automatically generates an index.

Related

MySQL Cluster - Composite foreign key error: Missing index for constraint

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.

Odd Cannot add foreign key constraint

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.

MYSQL Error - Duplicate key on write or update

CREATE TABLE IF NOT EXISTS `demare`.`shop` (
`shop_id` INT NOT NULL AUTO_INCREMENT,
`shop_image` VARCHAR(255) NOT NULL,
`shop_price` FLOAT(6,2) NOT NULL,
`cart_id` INT NOT NULL,
PRIMARY KEY (`shop_id`),
INDEX `cart_id_idx` (`cart_id` ASC),
CONSTRAINT `cart_id`
FOREIGN KEY (`cart_id`)
REFERENCES `demare`.`shopping cart` (`cart_id`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB;
I have an error. My 'shop' table cannot be created as I have error:
121 Duplicate key on write or update.
I have provided the codes. Can anyone tell me what the problem is?
Problem exist because the foriegn key exist in memory, if possible drop the database and start again.

Duplicate Key issue after lost connection even thou constraint does not exist

I was doing a migration on laravel for all my DB's (several clients). All DB are the same structure and one of them lost connection and failed before completion. I tried to migrate again and I ran into an issue with a duplicate foreign key.
After looking at the constraints
SELECT * FROM information_schema.KEY_COLUMN_USAGE ke where constraint_name = 'rt_eqmtfixedcycle_excav_id_foreign'
SQL result for schema
All other databases successfully inserted 'rt_eqmtfixedcycle_excav_id_foreign' key. But the one that failed 'smv_Forestalleonera' database did not appear, but.
If I try to insert again:
use smv_forestalleonera;
alter table `rt_eqmtfixedcycle` add constraint `rt_eqmtfixedcycle_excav_id_foreign` foreign key (`excav_id`) references `rt_truck` (`id`) on delete restrict on update cascade
I get the following error:
12:33:45 alter table `rt_eqmtfixedcycle`
add constraint `rt_eqmtfixedcycle_excav_id_foreign`
foreign key (`excav_id`)
references `rt_truck` (`id`)
on delete restrict
on update cascade Error Code: 1005. Can't create table `smv_forestalleonera`.`#sql-7f4d_a8f7` (errno: 121 "Duplicate key on write or update") 0.234 sec
I'm using MariaDB 10.2.7.
I've already removed the table and restarted the engine without any results.
(from comment)
CREATE TABLE rt_eqmtfixedcycle (
id smallint(5) unsigned NOT NULL,
excav_id smallint(5) unsigned DEFAULT NULL,
locload_id int(10) unsigned DEFAULT NULL,
locdump_id int(10) unsigned DEFAULT NULL,
updated_at datetime DEFAULT NULL,
updated_by int(10) unsigned DEFAULT NULL,
KEY rt_eqmtfixedcycle_id_foreign (id),
CONSTRAINT rt_eqmtfixedcycle_id_foreign
FOREIGN KEY (id) REFERENCES rt_truck (id) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Can't write; duplicate key in table 'UserSessions' Even pk name changed

I want to create two table AdminSessions and UserSessions to store the client session data. Both of them have a pk named sessionKey with the properties of PK, NN, UQ. When I try to do a forward engineering, I encounter Can't write; duplicate key in table 'UserSessions'. After reading this solution, I try to change the name of the pks to sessionKeya and sessionKeyb but it does not work.
How to solve this error?
Error Message
ERROR: Error 1022: Can't write; duplicate key in table 'UserSessions'
SQL
CREATE TABLE IF NOT EXISTS `CodeSpace`.`UserSessions` (
`sessionKey` VARCHAR(128) NOT NULL,
`userId` INT UNSIGNED NOT NULL,
`lastAccessTime` DATETIME NULL,
`ip` VARCHAR(45) NULL,
`expiryTime` DATETIME NULL,
PRIMARY KEY (`sessionKey`),
UNIQUE INDEX `userId_UNIQUE` (`userId` ASC),
UNIQUE INDEX `id_UNIQUE` (`sessionKey` ASC),
CONSTRAINT `fk_UserSession_1`
FOREIGN KEY (`userId`)
REFERENCES `CodeSpace`.`Users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB