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

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

Related

ER_FK_NO_INDEX_PARENT: Failed to add the foreign key constaint

Hey so I'm on my first project with a complexe database :)
I have created all of my tables and I am now updating them to add the Foreign Keys (I had an issue so I decided to add Foreign Keys after creating all the tables).
Here the ERR Diagram that describe the project : click to open
The exact error i get : ER_FK_NO_INDEX_PARENT: Failed to add the foreign key constaint. Missing index for constraint 'fk_user_in_org__org_roles1' in the referenced table 'org_roles'
I've searched my error but i didn't found a solution to my problem here some of the best I found :
Link 1
Link 2
The tables concerned (simplified) and the update command :
------------------
-- Tables setup --
------------------
-- A role is unique for an org but differents orgs can have a role that have the same label
CREATE TABLE IF NOT EXISTS students.org_roles (
`org_id` INT NOT NULL,
`label` VARCHAR(32) NOT NULL,
PRIMARY KEY (`org_id`, `label`))
ENGINE = InnoDB;
-- The users are unique
CREATE TABLE IF NOT EXISTS students.users (
`id` INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
UNIQUE INDEX id_UNIQUE (`id` ASC));
-- The orgs are unique
CREATE TABLE IF NOT EXISTS students.organizations (
`id` INT NOT NULL AUTO_INCREMENT,
`name` TEXT(64) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX id_UNIQUE (`id` ASC))
ENGINE = InnoDB;
-- The table that match a user in an org with a specified role (= label in the org_role table)
CREATE TABLE IF NOT EXISTS students.user_in_org (
`user_id` INT NOT NULL,
`org_id` INT NOT NULL,
`role` TEXT(32) NOT NULL,
PRIMARY KEY (`user_id`, `org_id`),
UNIQUE INDEX `user_id_UNIQUE` (`user_id` ASC));
------------------------
-- The update command --
------------------------
ALTER TABLE students.user_in_org ADD
(CONSTRAINT fk_user_in_org__users1
FOREIGN KEY (`user_id`) REFERENCES students.users(`id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT fk_user_in_org__organizations1
FOREIGN KEY (`org_id`) REFERENCES students.organizations(`id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT fk_user_in_org__org_roles1
FOREIGN KEY (`role`) REFERENCES students.org_roles(`label`)
ON DELETE RESTRICT
ON UPDATE CASCADE);
Thank you in advance for your help :)
And please forgive me if my english isn't that fluent :/
This can be because the table students.org_roles doesn't have Unique index in the field org_id, it is what error says
For
CONSTRAINT fk_user_in_org__org_roles1
FOREIGN KEY (`role`) REFERENCES students.org_roles(`label`)
You need a index on the table org_roles for the column label
CREATE TABLE IF NOT EXISTS students.org_roles (
`org_id` INT NOT NULL,
`label` VARCHAR(32) NOT NULL,
KEy (`label`),
PRIMARY KEY (`org_id`, `label`))
ENGINE = InnoDB;
In your origi8nal design you have a combined primary key so you can only make a reference to the combined primary key or define a new one for label
CREATE TABLE IF NOT EXISTS org_roles (
`org_id` INT NOT NULL,
`label` VARCHAR(32) NOT NULL,
PRIMARY KEY (`org_id`, `label`))
ENGINE = InnoDB;
-- The users are unique
CREATE TABLE IF NOT EXISTS users (
`id` INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
UNIQUE INDEX id_UNIQUE (`id` ASC));
-- The orgs are unique
CREATE TABLE IF NOT EXISTS organizations (
`id` INT NOT NULL AUTO_INCREMENT,
`name` TEXT(64) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX id_UNIQUE (`id` ASC))
ENGINE = InnoDB;
-- The table that match a user in an org with a specified role (= label in the org_role table)
CREATE TABLE IF NOT EXISTS user_in_org (
`user_id` INT NOT NULL,
`org_id` INT NOT NULL,
`role` TEXT(32) NOT NULL,
PRIMARY KEY (`user_id`, `org_id`),
UNIQUE INDEX `user_id_UNIQUE` (`user_id` ASC));
ALTER TABLE user_in_org ADD
(CONSTRAINT fk_user_in_org__users1
FOREIGN KEY (`user_id`) REFERENCES users(`id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT fk_user_in_org__organizations1
FOREIGN KEY (`org_id`) REFERENCES organizations(`id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT fk_user_in_org__org_roles1
FOREIGN KEY (`org_id`,`role`) REFERENCES org_roles(`org_id`,`label`)
ON DELETE RESTRICT
ON UPDATE CASCADE);
db<>fiddle here

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 in table for foreign key in sql

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.

MySQL ERROR 1005: Can't create table

I am trying to create a table but I keep getting Error 1005. ): Please help!
Executing SQL script in server
ERROR: Error 1005: Can't create table 'czhen_hockey_db.hockey_db' (errno: 150)
SQL Code:
-- -----------------------------------------------------
-- Table `czhen_hockey_db`.`hockey_db`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `czhen_hockey_db`.`hockey_db` (
`id` INT NOT NULL,
`Date` VARCHAR(45) NOT NULL,
`Time` VARCHAR(45) NOT NULL,
`rink_id` INT NOT NULL,
`division/team_id` INT NOT NULL,
`opponent_id` INT NOT NULL,
INDEX `fk_hockey_db_rink_idx` (`rink_id` ASC),
INDEX `fk_hockey_db_division/team1_idx` (`division/team_id` ASC),
INDEX `fk_hockey_db_opponent1_idx` (`opponent_id` ASC),
PRIMARY KEY (`id`),
CONSTRAINT `fk_hockey_db_rink`
FOREIGN KEY (`rink_id`)
REFERENCES `czhen_hockey_db`.`rink` (`rink_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_hockey_db_division/team1`
FOREIGN KEY (`division/team_id`)
REFERENCES `czhen_hockey_db`.`division/team` (`division/team_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_hockey_db_opponent1`
FOREIGN KEY (`opponent_id`)
REFERENCES `czhen_hockey_db`.`opponent` (`opponent_name`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
SQL script execution finished: statements: 8 succeeded, 1 failed
SQL 1005 is related to Foreign key problem. So please check whether "RINK", "OPPONENT" and "division/team" tables exist with specified primary keys.
I think for Opponent table you have to specify opponent_id as foreign key in place of opponent_name.
Please check
CREATE TABLE IF NOT EXISTS `czhen_hockey_db`.`hockey_db` (
`id` INT NOT NULL,
`Date` VARCHAR(45) NOT NULL,
`Time` VARCHAR(45) NOT NULL,
`rink_id` INT NOT NULL,
`division/team_id` INT NOT NULL,
`opponent_id` INT NOT NULL,
INDEX `fk_hockey_db_rink_idx` (`rink_id` ASC),
INDEX `fk_hockey_db_division/team1_idx` (`division/team_id` ASC),
INDEX `fk_hockey_db_opponent1_idx` (`opponent_id` ASC),
PRIMARY KEY (`id`),
CONSTRAINT `fk_hockey_db_rink`
FOREIGN KEY (`rink_id`)
REFERENCES `czhen_hockey_db`.`rink` (`rink_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_hockey_db_division/team1`
FOREIGN KEY (`division/team_id`)
REFERENCES `czhen_hockey_db`.`division/team` (`division/team_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_hockey_db_opponent1`
FOREIGN KEY (`opponent_id`)
REFERENCES `czhen_hockey_db`.`opponent` (`opponent_name`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB