MySQL duplicate key error - mysql

If I run this code all work well, but if uncomment last constraint, I got the following error:
Error Code: 1022. Can't write; duplicate key in table 'transfer'
but there no another key 'fk_component_id', what wrong with this code?
-- -----------------------------------------------------
-- Table `pcdb`.`transfer`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `pcdb`.`transfer` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`component_id` INT UNSIGNED NOT NULL,
`type` INT NULL,
`parent_id` INT UNSIGNED NULL,
`source_id` INT UNSIGNED NULL,
`contractor_id` INT UNSIGNED NULL,
`src_department_id` INT UNSIGNED NULL,
`dest_department_id` INT UNSIGNED NULL,
`session_id` INT UNSIGNED NOT NULL,
`count` INT UNSIGNED NOT NULL,
`comment` TEXT(65535) NULL,
`active` TINYINT(1) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
CONSTRAINT `fk_src_department_id`
FOREIGN KEY (`src_department_id`)
REFERENCES `pcdb`.`department` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_income_id`
FOREIGN KEY (`source_id`)
REFERENCES `pcdb`.`transfer` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_contractor_id`
FOREIGN KEY (`contractor_id`)
REFERENCES `pcdb`.`contractor` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_session_id`
FOREIGN KEY (`session_id`)
REFERENCES `pcdb`.`session` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_dest_department_id`
FOREIGN KEY (`dest_department_id`)
REFERENCES `pcdb`.`department` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_parent_id`
FOREIGN KEY (`parent_id`)
REFERENCES `pcdb`.`transfer` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION/*,
CONSTRAINT `fk_component_id`
FOREIGN KEY (`component_id`)
REFERENCES `pcdb`.`component` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION*/);

It sounds like you may already have a constraint with that name on a different table in the database. Try changing the name of that constraint to something like "fk_transfer_component_id" and see if you still get the error.

Related

Error Code: 1822. Failed to add the foreign key constraint

CREATE TABLE `branch` (
`BranchID` INT NOT NULL,
`BranchSuburb` varchar(255) NOT NULL,
`BranchState` char(3) NOT NULL,
PRIMARY KEY (`BranchID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `member` (
`MemberID` INT NOT NULL,
`MemberStatus` char(9) DEFAULT 'REGULAR',
`MemberName` varchar(255) NOT NULL,
`MemberAddress` varchar(255) NOT NULL,
`MemberSuburb` varchar(25) NOT NULL,
`MemberState` char(3) NOT NULL,
`MemberExpDate` DATE,
`MemberPhone` varchar(10),
PRIMARY KEY (`MemberID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `publisher` (
`PublisherID` INT NOT NULL,
`PublisherName` varchar(255) NOT NULL,
`PublisherAddress` varchar(255) DEFAULT NULL,
PRIMARY KEY (`PublisherID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `book` (
`BookID` INT NOT NULL,
`BookTitle` varchar(255) NOT NULL,
`PublisherID` INT NOT NULL,
`PublishedYear` INT4,
`Price` Numeric(5,2) NOT NULL,
PRIMARY KEY (`BookID`),
KEY `PublisherID` (`PublisherID`),
CONSTRAINT `publisher_fk_1` FOREIGN KEY (`PublisherID`) REFERENCES `publisher` (`PublisherID`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `author` (
`AuthorID` INT NOT NULL,
`AuthorName` varchar(255) NOT NULL,
`AuthorAddress` varchar(255) NOT NULL,
PRIMARY KEY (`AuthorID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `authoredby` (
`BookID` INT NOT NULL,
`AuthorID` INT NOT NULL,
PRIMARY KEY (`BookID`,`AuthorID`),
KEY `bookID` (`BookID`),
KEY `AuthorID` (`AuthorID`),
CONSTRAINT `book_fk_1` FOREIGN KEY (`BookID`) REFERENCES `book` (`bookID`) ON DELETE RESTRICT,
CONSTRAINT `author_fk_1` FOREIGN KEY (`AuthorID`) REFERENCES `author` (`AuthorID`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `holding` (
`BranchID` INT NOT NULL,
`BookID` INT NOT NULL,
`InStock` INT DEFAULT 1,
`OnLoan` INT DEFAULT 0,
PRIMARY KEY (`BranchID`,`BookID`),
KEY `bookID` (`BookID`),
KEY `BranchID` (`BranchID`),
CONSTRAINT `holding_cc_1` CHECK(`InStock`>=`OnLoan`),
CONSTRAINT `book_fk_2` FOREIGN KEY (`BookID`) REFERENCES `book` (`bookID`) ON DELETE RESTRICT,
CONSTRAINT `branch_fk_1` FOREIGN KEY (`BranchID`) REFERENCES `branch` (`BranchID`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `borrowedby` (
`BookIssueID` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`BranchID` INT NOT NULL,
`BookID` INT NOT NULL,
`MemberID` INT NOT NULL,
`DateBorrowed` DATE,
`DateReturned` DATE DEFAULT NULL,
`ReturnDueDate` DATE,
PRIMARY KEY (`BookIssueID`),
KEY `bookID` (`BookID`),
KEY `BranchID` (`BranchID`),
KEY `MemberID` (`MemberID`),
CONSTRAINT `borrowedby_cc_1` CHECK(`DateBorrowed`<`ReturnDueDate`),
CONSTRAINT `holding_fk_1` FOREIGN KEY (`BookID`,`BranchID`) REFERENCES `holding` (`BookID`,`BranchID`) ON DELETE RESTRICT,
CONSTRAINT `member_fk_1` FOREIGN KEY (`MemberID`) REFERENCES `member` (`MemberID`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Im getting the following error when i try to execute the last create query for the borrowedby table.
Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'holding_fk_1' in the referenced table 'holding'
have you tried to split the double foreign key? like this:
CONSTRAINT `holding_fk_1` FOREIGN KEY (`BookID`) REFERENCES `holding` (`BookID`) ON DELETE RESTRICT,
CONSTRAINT `holding_fk_1` FOREIGN KEY (`BranchID`) REFERENCES `holding` (`BranchID`) ON DELETE RESTRICT
what dms are you using? could be that you need to use another syntax to reference two foreign key at one or could be that it's not supported.
As said in the answer, just by changing order can fix it.
"Your code fails in Mysql 8.0.12 but runs fine in 8.0.22 As a workaround reverse the order of the columns: CONSTRAINT holding_fk_1 FOREIGN KEY (BranchID,BookID) REFERENCES holding (BranchID,BookID) ON DELETE RESTRICT, –
forpas
Oct 27 '20 at 15:50 "

Table in mySQL that has several foreign keys that are primary key, getting an error ERROR 1215: Cannot add foreign key constraint

I had created those tables:
CREATE TABLE `course` (
`idcourse` varchar(2) NOT NULL,
`courseName` varchar(45) NOT NULL,
`subjectID` varchar(2) NOT NULL,
PRIMARY KEY (`idcourse`),
KEY `subjectID_idx` (`subjectID`),
CONSTRAINT `subjectID` FOREIGN KEY (`subjectID`) REFERENCES `subject` (`idsubject`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `exam` (
`subjectID` varchar(2) NOT NULL,
`courseID` varchar(2) NOT NULL,
`examNumber` varchar(2) NOT NULL,
`duration` int(11) DEFAULT NULL,
PRIMARY KEY (`subjectID`,`courseID`,`examNumber`),
KEY `idCourse_idx` (`courseID`),
CONSTRAINT `idCo` FOREIGN KEY (`courseID`) REFERENCES `course` (`idcourse`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `idSu` FOREIGN KEY (`subjectID`) REFERENCES `subject` (`idsubject`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `question` (
`questionText` varchar(100) DEFAULT NULL,
`answer1` varchar(100) DEFAULT NULL,
`answer2` varchar(100) DEFAULT NULL,
`answer3` varchar(100) DEFAULT NULL,
`answer4` varchar(100) DEFAULT NULL,
`subjetID` varchar(2) NOT NULL,
`questionNumber` varchar(3) NOT NULL,
`rightAnswer` int(4) DEFAULT NULL,
PRIMARY KEY (`subjetID`,`questionNumber`),
CONSTRAINT `idsubject` FOREIGN KEY (`subjetID`) REFERENCES `subject` (`idsubject`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `subject` (
`idsubject` varchar(2) NOT NULL,
`subjectName` varchar(45) NOT NULL,
PRIMARY KEY (`idsubject`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
To subject table I add a record:
idsubject = 02, subjectName = Mathematica
To course table I add a record:
idcourse = 03, courseName = Algebra 1, subjectID = 02
To exam table I add a record:
subjectID = 02, courseID = 03, examNumber = 01, duration = 180
Now, I want to create a table: questionsinexam
CREATE TABLE `test`.`questionsinexam` (
`idExamSubject` VARCHAR(2) NOT NULL,
`idExamCourse` VARCHAR(2) NOT NULL,
`idExamNumber` VARCHAR(2) NOT NULL,
`idQuestionNumber` VARCHAR(3) NOT NULL,
`pointsPerQuestion` INT NULL,
PRIMARY KEY (`idExamSubject`, `idExamCourse`, `idExamNumber`, `idQuestionNumber`),
INDEX `idExamCourse_idx` (`idExamCourse` ASC),
INDEX `idExamNumber_idx` (`idExamNumber` ASC),
INDEX `idQuestionNumber_idx` (`idQuestionNumber` ASC),
CONSTRAINT `idExamSubject`
FOREIGN KEY (`idExamSubject`)
REFERENCES `test`.`exam` (`subjectID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `idExamCourse`
FOREIGN KEY (`idExamCourse`)
REFERENCES `test`.`exam` (`courseID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `idExamNumber`
FOREIGN KEY (`idExamNumber`)
REFERENCES `test`.`exam` (`examNumber`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `idQuestionNumber`
FOREIGN KEY (`idQuestionNumber`)
REFERENCES `test`.`question` (`questionNumber`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
Why I'm getting this error?
Thanks.
This constraint is definitely wrong:
CONSTRAINT `idExamSubject`
FOREIGN KEY (`idExamSubject`)
REFERENCES `test`.`exam` (`subjectID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
Perhaps you intend:
CONSTRAINT `idExamSubject`
FOREIGN KEY (`idExamSubject`)
REFERENCES `test`.`subject` (`subjectID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
Be sure that you create the target tables before you create the foreign key constraint. The referred to table needs to exist first (so the engine can validate types on the columns used for the foreign key).

Foreign key constraint fails even when data types are the same

I'm building a table with a two part foreign key that references a two part key in another table. It isn't working, and I can't see why because the data types line up.
Can't create table 'tsugi.video_comments' (errno: 150)
Here's the code I'm trying to run:
CREATE TABLE `video_comments` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`video_id` varchar(11) NOT NULL DEFAULT '',
`link_id` int(11) NOT NULL,
`videoTime` int(11) NOT NULL,
`comment` text NOT NULL,
`parent` int(11) unsigned DEFAULT NULL,
`private` tinyint(1) DEFAULT NULL,
`replies` int(11) unsigned DEFAULT '0',
`reports` int(11) DEFAULT '0',
`user_id` int(11) NOT NULL,
`displayname` varchar(2048) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `video_ibfk_1` (`link_id`),
KEY `video_ibfk_2` (`user_id`),
CONSTRAINT `video_comments_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `video_comments` (`id`) ON DELETE CASCADE,
CONSTRAINT `video_ibfk_1` FOREIGN KEY (`link_id`) REFERENCES `lti_link` (`link_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `video_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `lti_user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `video_key` FOREIGN KEY (`link_id`, `video_id`) REFERENCES `video_ids` (`link_id`, `video_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=285 DEFAULT CHARSET=utf8;
The command runs successfully if I delete the last constraint, so that's where the problem is, not in the other constraints.
Here's the table it's referencing:
CREATE TABLE `video_ids` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`video_id` varchar(11) NOT NULL DEFAULT '',
`link_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `video_key` (`video_id`,`id`),
KEY `link_id` (`link_id`),
KEY `id` (`id`,`video_id`),
CONSTRAINT `video_ids_ibfk_1` FOREIGN KEY (`link_id`) REFERENCES `t_lti_link` (`link_id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
To make sure that the video_id and link_id fields are exactly the same, I copied them directly from the existing table's code to the code for creating the new table. I expected that to solve it, but it did not. Here's the error log:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
141114 22:04:09 Error in foreign key constraint of table tsugi/video_comments:
FOREIGN KEY (`link_id`, `video_id`) REFERENCES `video_ids` (`link_id`, `video_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=285 DEFAULT CHARSET=utf8:
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.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Foreign key references need to be to unique or primary keys. So, you can fix this just by having a unique declaration in video_ids:
CREATE TABLE `video_ids` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`video_id` varchar(11) NOT NULL DEFAULT '',
`link_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `video_key` (`video_id`,`id`),
KEY `link_id` (`link_id`),
KEY `id` (`id`,`video_id`),
UNIQUE (link_id, video_id),
CONSTRAINT `video_ids_ibfk_1` FOREIGN KEY (`link_id`) REFERENCES `t_lti_link` (`link_id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
Here is a SQL Fiddle with an example.

MySQL foreign key failure on create but not alter statement

The below SQL fails. with "#1005 - Can't create table 'scheduler_appointmentLog' (errno: 150)"
CREATE TABLE IF NOT EXISTS `scheduler_appointment` (
`id` INT NOT NULL AUTO_INCREMENT,
`timeAdded` INT NOT NULL,
`timeModified` INT NOT NULL,
`core_office_id` INT NOT NULL,
`core_patrparty_id` INT NOT NULL,
`core_procedure_id` INT NOT NULL,
`core_staff_id_dr` INT NOT NULL,
`scheduler_appointmentStatus_id` INT NOT NULL,
`scheduler_chair_id` INT NOT NULL,
`apptDate` DATE NULL,
`startTime` TIME NULL,
`endTime` TIME NULL,
`arrivedTime` TIME NULL,
`seatTime` TIME NULL,
`readyForDoctor` TIME NULL,
`frontDeskTime` TIME NULL,
`departTime` TIME NULL,
`comment` LONGTEXT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `fk_scheduler_appointment_scheduler_appointmentRequest1`
FOREIGN KEY (`id`)
REFERENCES `scheduler_appointmentRequest` (`scheduler_appointment_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_scheduler_appointment_financial_payschedQ1`
FOREIGN KEY (`id`)
REFERENCES `financial_payschedQ` (`scheduler_appointment_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_scheduler_appointment_financial_chargeLog1`
FOREIGN KEY (`id`)
REFERENCES `financial_chargeLog` (`scheduler_appointment_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_scheduler_appointment_scheduler_appointmentLog1`
FOREIGN KEY (`id`)
REFERENCES `scheduler_appointmentLog` (`scheduler_appointment_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
HOWEVER if i turn it into 2 statements it works. The Create table in one statement and the constraints in the other.
This will add the table with no errors.
CREATE TABLE IF NOT EXISTS `scheduler_appointment` (
`id` INT NOT NULL AUTO_INCREMENT,
`timeAdded` INT NOT NULL,
`timeModified` INT NOT NULL,
`core_office_id` INT NOT NULL,
`core_patrparty_id` INT NOT NULL,
`core_procedure_id` INT NOT NULL,
`core_staff_id_dr` INT NOT NULL,
`scheduler_appointmentStatus_id` INT NOT NULL,
`scheduler_chair_id` INT NOT NULL,
`apptDate` DATE NULL,
`startTime` TIME NULL,
`endTime` TIME NULL,
`arrivedTime` TIME NULL,
`seatTime` TIME NULL,
`readyForDoctor` TIME NULL,
`frontDeskTime` TIME NULL,
`departTime` TIME NULL,
`comment` LONGTEXT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
And this will add the constraint with no errors.
ALTER TABLE `scheduler_appointment` ADD
CONSTRAINT `fk_scheduler_appointment_scheduler_appointmentRequest1`
FOREIGN KEY (`id`)
REFERENCES `scheduler_appointmentRequest` (`scheduler_appointment_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
EDIT...
Working export from phpMyAdmin to show mine is not backwards.
ALTER TABLE `scheduler_appointment`
ADD CONSTRAINT `fk_scheduler_appt_financial_payschedQ1` FOREIGN KEY (`id`) REFERENCES `financial_payschedQ` (`scheduler_appointment_id`),
ADD CONSTRAINT `fk_scheduler_appointment_financial_payschedQ1` FOREIGN KEY (`id`) REFERENCES `financial_payschedQ` (`scheduler_appointment_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_scheduler_appointment_scheduler_appointmentLog1` FOREIGN KEY (`id`) REFERENCES `scheduler_appointmentLog` (`scheduler_appointment_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_scheduler_appointment_scheduler_appointmentRequest1` FOREIGN KEY (`id`) REFERENCES `scheduler_appointmentRequest` (`scheduler_appointment_id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
I guess i need help to understand why the ALTER table will add it to the database but it can not be done in the create table statement. If they both failed i would not bother asking, but one works and one doesnt. If MySQL Workbench would export as ALTER statements (like phpMyAdmin does) instead of inline statements then i also wouldn't care to know the answer. However i am stuck needing to know to make the exported file from workbench to load into phpMyAdmin.

Why can't I add a foreign key constraint this way?

Tables:
CREATE TABLE `relation` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
`gender` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_relation` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `invite` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`date_sent` date NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`relation_id` int(10) unsigned NOT NULL,
`email` varchar(255) NOT NULL,
`code` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_user` (`user_id`),
CONSTRAINT `fk_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8
The SQL statement executed was:
ALTER TABLE `invite`
ADD CONSTRAINT `fk_relation`
FOREIGN KEY (`relation_id`)
REFERENCES `relation` (`id`)
ON DELETE CASCADE ON UPDATE RESTRICT
Mysql Error:
SQLSTATE[HY000]: General error: 1005 Can't create table 'dbtest.#sql-d00_39' (errno: 121).
The relation.id and invite.relation_id columns are of the same type int(10) unsigned
UPDATE
The table invite is empty while adding this key.
The table relation has 3 rows.
try this :
ALTER TABLE invite
ADD CONSTRAINT fk_relation
FOREIGN KEY (relation_id)
REFERENCES relation(id)
According to the doc syntax is correct SQL FOREIGN KEY Constraint
The DDL for Foreign Key creation now automatically includes statements to specify actions on "Delete" and "Update". However, for "Delete", it includes the statement "ON DELETE RESTRICT", which does not appear to be a valid T-SQL statement.
TRY THIS :
ALTER TABLE invite WITH CHECK ADD CONSTRAINT fk_relation
FOREIGN KEY (relation_id) REFERENCES relation (id)