MySQL duplicate key in table - mysql

I have an error with the following SQL query and I'm not sure how to fix it. The error message is:
"Error Code: 1022. Can't write; duplicate key in table
't_course_catalog'"
Here is the query:
CREATE TABLE IF NOT EXISTS `TrainingPlan`.`T_Course_Catalog` (
`CC_ID` INT NOT NULL AUTO_INCREMENT,
`ID_Catalog_Level` INT NOT NULL,
`Catalog_Name` VARCHAR(50) NOT NULL,
`ID_Delivery_Method` INT NOT NULL,
`Created_Date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`Created_By` VARCHAR(8) NOT NULL,
`Modified_Date` TIMESTAMP NULL,
`Modified_By` VARCHAR(8) NULL,
`Deleted` TINYINT(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`CC_ID`),
INDEX `fk_cl_idx` (`ID_Catalog_Level` ASC),
INDEX `fk_dm_idx` (`ID_Delivery_Method` ASC),
CONSTRAINT `fk_cl`
FOREIGN KEY (`ID_Catalog_Level`)
REFERENCES `TrainingPlan`.`T_Catalog_Level` (`CL_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_dm`
FOREIGN KEY (`ID_Delivery_Method`)
REFERENCES `TrainingPlan`.`T_Delivery_Method` (`DM_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
It should be no problem to reference the foreign keys because the reference table exists.

Try renaming your constraints, they are probably duplicated somewhere in your database.
Example :
fk_cl becomes fk_course_catalog_cl
fk_dm become fk_course_catalog_dm
Or w/e alternative name you want it to be.

Related

Foreign Key constraint error even without a foreign key

I am getting the following error:
Error Code: 1215. Cannot add foreign key constraint
This happens even if I remove all foreign key constraints. timeline table does exist in the database, so that is not the issue.
Can't seem to figure out what would cause this problem
USE study;
CREATE TABLE IF NOT EXISTS timelineStage(
timelineStageID INT NOT NULL AUTO_INCREMENT,
timelineID TINYINT NOT NULL,
stageName VARCHAR(100) NOT NULL,
stagePredecessorID INT NULL,
isStartup TINYINT NOT NULL DEFAULT 0,
timelineStageNotes VARCHAR(500) NULL,
recCreatedByUserID INT NOT NULL,
recCreatedTimeUTC TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
recUpdatedByUserID INT NOT NULL,
recUpdatedTimeUTC TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (timelineStageID),
UNIQUE KEY IX_U_timelineStage_stageName(stageName, timelineID),
UNIQUE KEY IX_U_timelineStage_stagePredecessor(stagePredecessorID, timelineID),
CONSTRAINT FK_timelineStage_timelineID
FOREIGN KEY (timelineID)
REFERENCES timeline(timelineID)
ON UPDATE CASCADE,
CONSTRAINT FK_timelineStage_stagePredecessorID
FOREIGN KEY (stagePredecessorID)
REFERENCES timelineStage(timelineStageID)
ON UPDATE CASCADE,
CONSTRAINT FK_timelineStage_recCreatedByUserID
FOREIGN KEY (recCreatedByUserID)
REFERENCES customer.user(userID)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT FK_timelineStage_recUpdatedByUserID
FOREIGN KEY (recUpdatedByUserID)
REFERENCES customer.user(userID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ADDING Timeline and customer.user
USE study;
CREATE TABLE timeline(
timelineID TINYINT NOT NULL AUTO_INCREMENT,
timelineName VARCHAR(100) NOT NULL,
timelineNotes VARCHAR(500) NULL,
recCreatedByUserID INT(11) NOT NULL,
recCreatedTimeUTC DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
recUpdatedByUserID INT(11) NOT NULL,
recUpdatedTimeUTC TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (timelineID)
)
CREATE TABLE customer.user(
userID INT NOT NULL AUTO_INCREMENT,
firstName VARCHAR(100) NOT NULL,
lastName VARCHAR(100) NOT NULL,
emailAddress VARCHAR(100) NOT NULL,
PRIMARY KEY (userID))
The problem was with neither of the other tables. It was is study table (another table).
timelineStageID was set to TINYINT and in timelineStage table timelineStageID was set to INT.
Matching all to INT fixed the problem.
Carefully check every references clause whether the referenced column really is present in the table.
Also try to first create the table and then add the constraints one by one so you exactly know which one failed.
The problem is about this code: REFERENCES customer.user
You cannot create a foreign key constraint referencing a table in another database.

Mysql Connot add foreign key constraint. how can I resolve it?

I tried to excute the query. but a error was occurred. the error message is 'Cannot add foreign key constraint'.
I supposed to create this table. but it didn't work.
CREATE TABLE IF NOT EXISTS `mydb`.`member` (
`idseq` INT(1) NOT NULL AUTO_INCREMENT,
`id` VARCHAR(50) NOT NULL,
`pw` VARCHAR(20) NOT NULL,
`name` VARCHAR(50) NOT NULL,
`email` VARCHAR(45) NOT NULL,
`mobile0` VARCHAR(3) NOT NULL,
`mobile1` VARCHAR(3) NOT NULL,
`mobile2` VARCHAR(4) NOT NULL,
`mobile3` VARCHAR(4) NOT NULL,
`birth` DATE NOT NULL,
`admin_YN` VARCHAR(45) NOT NULL DEFAULT 'N',
`reg_date` DATE NOT NULL,
`upd_date` DATE NOT NULL,
PRIMARY KEY (`idseq`, `id`))
ENGINE = InnoDB
AUTO_INCREMENT = 6
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `mydb`.`reservation` (
`reservation_seq` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` VARCHAR(50) NOT NULL,
`playMv_seq` INT(11) NOT NULL,
`reservaion_seat_code` VARCHAR(20) NOT NULL,
`reservaion_seat_num` INT(11) NOT NULL,
`reservation_charge` VARCHAR(20) NOT NULL,
`reservation_date` DATETIME NOT NULL,
PRIMARY KEY (`reservation_seq`, `user_id`, `playMv_seq`),
FOREIGN KEY (`user_id`)
REFERENCES `mydb`.`member` (`id`)
)
ENGINE = InnoDB
AUTO_INCREMENT = 8
DEFAULT CHARACTER SET = utf8;
So I checked it detail from a query'show engine innodb status. the detail error message is
Error in foreign key constraint of table mydb/reservation:
FOREIGN KEY (`user_id`)
REFERENCES `mydb`.`member` (`id`)
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.
how can I resolve the error
You're trying to create a foreign key referencing the id column of the target table:
FOREIGN KEY (`user_id`)
REFERENCES `mydb`.`member` (`id`)
But what is the actual key on that target table?:
PRIMARY KEY (`idseq`, `id`)
It's not id, if the composite of idseq and id. In order to reference that as a foreign key, you need local columns which match that:
`user_idseq` INT(1) NOT NULL,
`user_id` VARCHAR(50) NOT NULL,
And use both of them for the foreign key:
FOREIGN KEY (`user_idseq`, `user_id`)
REFERENCES `mydb`.`member` (`idseq`, `id`)
(Side Note: That primary key in member looks pretty strange to me in the first place. Why can't idseq by itself be the primary key? What is the purpose of id?)

Mysql: using two foreign keys to the same table

I'm using MySQL workbench to design a database. Server is mysql 5.5.6
I've defined a few foreign keys linking the "candidates" table to the "countries" table. I get this error:
Executing SQL script in server
ERROR: Error 1005: Can't create table 'customer.candidats' (errno: 150)
The thing is: i'm referencing twice the countries table: once for the "nationality" column, once for the user address's country of origin. Is that allowed? Is this the right way to do it?
Here is the generated code that seems to trigger the issue.
CREATE TABLE IF NOT EXISTS `customer`.`candidats` (
`id` INT NOT NULL AUTO_INCREMENT,
`nom` VARCHAR(40) NULL,
`prenom` VARCHAR(40) NULL,
`qualite` ENUM('0001','0002') NULL COMMENT '0001 = Madame\n0002 = Monsieur',
`sexe` SET('1','2') NULL COMMENT '1 = Femme\n2 = Homme',
`date_de_naissance` DATE NULL,
`Nationalite` INT NOT NULL,
`selor_bilinguisme` TINYINT(1) NULL,
`rue` VARCHAR(60) NULL,
`numero` VARCHAR(10) NULL,
`pays` INT NOT NULL,
`region` INT NOT NULL,
`localité` VARCHAR(40) NULL,
`code_postal` VARCHAR(10) NULL,
`email` VARCHAR(241) NULL,
`tel_domicile` VARCHAR(30) NULL,
`tel_bureau` VARCHAR(30) NULL,
`tel_mobile` VARCHAR(30) NULL,
`tel_prefere` ENUM('01','02','03') NULL DEFAULT '03',
PRIMARY KEY (`id`),
INDEX `fk_candidats_pays_idx` (`Nationalite` ASC, `pays` ASC),
INDEX `fk_candidats_régions1_idx` (`region` ASC),
CONSTRAINT `fk_candidats_pays`
FOREIGN KEY (`Nationalite` , `pays`)
REFERENCES `customer`.`pays` (`id` , `id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_candidats_régions1`
FOREIGN KEY (`region`)
REFERENCES `customer`.`régions` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
The "pays" table ("countries" in French)
CREATE TABLE IF NOT EXISTS `customer`.`pays` (
`id` INT NOT NULL AUTO_INCREMENT,
`nom_fr` VARCHAR(45) NULL,
`nom_nl` VARCHAR(45) NULL,
`nationalite_fr` VARCHAR(45) NULL,
`nationalite_nl` VARCHAR(45) NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `id_UNIQUE` (`id` ASC))
ENGINE = InnoDB
Your schema generator doesn't work correctly.
It should generate:
CONSTRAINT `fk_candidats_pays`
FOREIGN KEY (`pays`)
REFERENCES `customer`.`pays` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_candidats_Nationalite`
FOREIGN KEY (`Nationalite`)
REFERENCES `customer`.`pays` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
To your other question: This type of referencing seems strange when you see it the first time, but it's quite normal and I think there is no other way of constructing this type of relationship.

Shortcut Assign Primary Key while create table

What is the right way to assign primary key with shortcut query while creating table?
Here is the example how my shortcut it is:
create table booking_product (
`id` int(10) not null constraint `booking_product_id` primary key auto_increment ,
`bookingId` int(10) not null,
`serviceId` int(10) not null,
`date` date not null,
`price` decimal(30,15) not null,
`qty` int(1) not null,
`currencyId` int(10) not null,
`total` decimal(30,15) not null,
`roomInclusion` text null default null,
foreign key booking_product(bookingId) references booking(id) on update cascade on delete cascade,
foreign key booking_product(serviceId) references service(id) on update cascade on delete set null,
foreign key booking_product(currencyId) references currency(id) on update cascade on delete set null
) engine = InnoDB;
notice on line 2 I tried to assign primary key, but this query is wrong and produce error. If I try to only use id int(10) not null primary key auto_increment , I get error: Duplicate key name 'booking_product'
If you use constraint booking_product_id, you don't get errors about Duplicate key name 'booking_product' because the SQL parser stops at the first error.
Drop constraint booking_product_id and use
foreign key bookingId_fk(bookingId) references booking(id)
on update cascade
on delete cascade,
foreign key serviceId_fk(serviceId) references service(id)
on update cascade
on delete set null,
foreign key currencyId_fk(currencyId) references currency(id)
on update cascade
on delete set null
I know you picked an answer but when I simplified just your create statement to the code below I got it to work. Now with the added 'drop constraint' request by Oswald you might have everything you want:
create table booking_product (
id int(10) not null auto_increment,
PRIMARY KEY(id), <<<<< this worked for me...
bookingId int(10) not null,
serviceId int(10) not null,
date date not null,
price decimal(30,15) not null,
qty int(1) not null,
currencyId int(10) not null,
total decimal(30,15) not null,
roomInclusion text null default null)
Again I am only approaching the question from what you asked which was assigning a primary.
Hope this helps.

on duplicate key update fails with error "Cannot add or update a child row"

I have a table with a compound primary key "name" and "id". The fields are actually "name","id","phone","amount","units","alias". I have the query
insert into MyTable (name,id,phone,amount) select "henry" as name, id,phone,amount from anotherTable
on duplicate key update phone=values(phone),amount=values(amount).
MySQL spits the following error:
Cannot add or update a child row: a foreign key constraint fails.
BTW, "id" is a foreign key.
Any help?
as requested below, the schema for other table is
CREATE TABLE `otherTable` (
`otherId` int(11) NOT NULL AUTO_INCREMENT,
`DOBId` int(11) NOT NULL,
`bankAccount` int(11) DEFAULT NULL,
`partialAmount` int(11) NOT NULL DEFAULT '0',
`id` int(11) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`notes` varchar(299) DEFAULT NULL,
`latitude` decimal(8,5) DEFAULT NULL,
`longitude` decimal(8,5) DEFAULT NULL,
PRIMARY KEY (`otherId `),
KEY `DOBId ` (`DOBId `),
KEY `bankAccount ` (`bankAccount `),
KEY `id ` (`id `)
) ENGINE=InnoDB AUTO_INCREMENT=3305 DEFAULT CHARSET=utf8;
for myTable
CREATE TABLE `myTable` (
`name` int(11) NOT NULL,
`id` int(11) NOT NULL,
`appleNumber` int(11) DEFAULT NULL,
`amount` int(11) DEFAULT NULL,
`windowsNumber` int(11) DEFAULT NULL,
`phone` int(11) DEFAULT NULL,
`pens` int(11) DEFAULT NULL,
`pencils` int(11) DEFAULT NULL,
PRIMARY KEY (`name`,`id`),
KEY `id` (`id`),
CONSTRAINT `myTable_ibfk_1` FOREIGN KEY (`id`) REFERENCES `yet_another` (`id`)
The problem appears to be that the FK constraint you have on myTable is referencing the ids of yet_another, so when you are inserting ids from anotherTable you are breaking this FK constraint. Chances are there are ids in anotherTable that do not exist in yet_another table.
Understand this is a shot in the dark, based on the abstracted schema you posted. If you want a more solid answer, I'd have to see the actual schema.
The on duplicate key applies to the primary key. I take it you're using innodb. This is failing on a foreign key constraint. Which values of you table MyTable are foreign keys? Please post the create statement for the table that shows all keys and constraints for more detailed help.
Just a guess, but for grins I'm betting it's a column that's not in the insert that is a foreign key not allowing a null value.