Creating composite primarykey using a foreignkey and a non key attribute - mysql

This is my auto generated code after creating the batch table. while inserting data to this table
BatchID=1,Course_CourseID=1
BatchID=1,Course_CourseID=2
it is creating an error saying "Duplicate entry '1' for key 'BatchID_UNIQUE'".
I'm using C# 2010 express windows application as well as MySQl 5.1
My table schema is here
CREATE TABLE `batch` (
`BatchID` int(11) NOT NULL,
`Course_CourseID` int(11) NOT NULL,
`NoOfStudents` int(11) DEFAULT NULL,
`ClassRoom` varchar(45) DEFAULT NULL,
`StartDate` varchar(45) DEFAULT NULL,
`Day` varchar(45) DEFAULT NULL,
`Time` varchar(45) DEFAULT NULL,
PRIMARY KEY (`BatchID`,`Course_CourseID`),
UNIQUE KEY `BatchID_UNIQUE` (`BatchID`),
KEY `fk_Batch_Course1` (`Course_CourseID`),
CONSTRAINT `fk_Batch_Course1` FOREIGN KEY (`Course_CourseID`)
REFERENCES `course` (`CourseID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Well, the error message quite clearly refers to this string:
UNIQUE KEY `BatchID_UNIQUE` (`BatchID`)
So what you have to do is either drop this index (with...
ALTER TABLE `batch` DROP INDEX `BatchID_UNIQUE`
... command, or just exclude this line from the table's definition (in CREATE TABLE).
All that said assuming that you really don't need your batch ids to be unique (in other words, there's no logical error in your INSERT statement. That seems to be the case, though: pair BatchID-Course_CourseID is already defined as unique (via PRIMARY KEY).

Try it this way. Drop your batch table and then run this sql. Rightly answered that you can not have two same vaues for a unique key. So I removed the unique key line as well.
CREATE TABLE IF NOT EXISTS `batch` (
`BatchID` int(11) NOT NULL,
`Course_CourseID` int(11) NOT NULL,
`NoOfStudents` int(11) DEFAULT NULL,
`ClassRoom` varchar(45) DEFAULT NULL,
`StartDate` varchar(45) DEFAULT NULL,
`Day` varchar(45) DEFAULT NULL,
`Time` varchar(45) DEFAULT NULL,
PRIMARY KEY (`BatchID`,`Course_CourseID`),
KEY `Course_CourseID` (`Course_CourseID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `batch` ADD CONSTRAINT `batch_ibfk_2` FOREIGN KEY (`Course_CourseID`)
REFERENCES `course` (`CourseId`) ON DELETE NO ACTION ON UPDATE NO ACTION;

Related

Error creating foreign key on userid, followerid (check data types)

Hey I'm having issues setting foreign keys pointing from my followings table:
CREATE TABLE `followings` (
`id` int(26) NOT NULL,
`userid` varchar(256) NOT NULL,
`followerid` varchar(256) NOT NULL,
`time` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
to my users table:
CREATE TABLE `users` (
`id` int(26) NOT NULL,
`userid` varchar(256) NOT NULL,
`handle` varchar(256) NOT NULL,
`email` varchar(256) NOT NULL,
`password` varchar(256) NOT NULL,
`phone` varchar(256) NOT NULL,
`dateofbirth` varchar(99) NOT NULL,
`phoneverified` varchar(25) DEFAULT NULL,
`emailverified` varchar(25) DEFAULT NULL,
`authentic` tinyint(1) NOT NULL DEFAULT 0,
`datecreated` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `userid` (`userid`),
ADD UNIQUE KEY `handle` (`handle`);
I have checked the collation etc of the fields are the same yet i am still getting an error on phpmyadmin
Error creating foreign key on userid, followerid (check data types)
Any possible reasons for such error
This is the sql generated by phpmyadmin before the error
ALTER TABLE `followings` ADD FOREIGN KEY (`userid`, `followerid`) REFERENCES `users`(`userid`, `userid`) ON DELETE RESTRICT ON UPDATE RESTRICT;
You shouldn't be making a multi-key foreign key. You need separate foreign keys for userid and followerid, since they refer to different rows in the users table.
ALTER TABLE followings ADD FOREIGN KEY (userid) REFERENCES users (userid);
ALTER TABLE followings ADD FOREIGN KEY (followerid) REFERENCES users (userid);
Also, it's usually preferable to have the foreign key reference the primary key.

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 Error 1215: Cannot add foreign key constraint between Parent and Children

I am utterly disappointed as I failed to pinpoint to the exact reason, why my table creation is failing when I am trying to create a Foreign Key relation between my two tables. The SQL queries that I am using to create the 2 tables are as under:
CREATE TABLE `OneMD_DEA_EMEA_STG_CUSTOMER` (
`Customer_Pkey` int(11) NOT NULL AUTO_INCREMENT,
`CustomerID` varchar(15) NOT NULL,
`DataType` varchar(10) NOT NULL,
`SourceSystemName` varchar(10) NOT NULL,
`SourceCountry` varchar(2) NOT NULL,
`SrcDataRfrshDt` date NOT NULL,
`StartDt` date NOT NULL,
`EndDt` date NOT NULL,
`Category` varchar(50) DEFAULT NULL,
PRIMARY KEY (`Customer_Pkey`,`CustomerID`),
UNIQUE KEY `CustomerID_UNIQUE` (`CustomerID`),
KEY `idx_OneMD_DEA_EMEA_STG_CUSTOMER` (`DataType`,`SrcDataRfrshDt`,`SourceCountry`,`EndDt`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `STG_RELATION` (
`Relation_Pkey` int(11) NOT NULL AUTO_INCREMENT,
`RelationType` varchar(15) NOT NULL,
`SourceDataType` varchar(5) NOT NULL,
`SourceID` varchar(15) NOT NULL,
`TargetDataType` varchar(5) NOT NULL,
`TargetID` varchar(15) NOT NULL,
`RltnPrmryID` varchar(50) NOT NULL,
`SourceSystemName` varchar(10) DEFAULT NULL,
`SourceCountry` varchar(2) NOT NULL,
`SrcDataRfrshDt` date NOT NULL,
`StartDt` date NOT NULL,
`EndDt` date NOT NULL,
`HCPHCOSubType` varchar(10) DEFAULT NULL,
`HCPHCOLinkType` varchar(10) DEFAULT NULL,
`HCOHCOSubType` varchar(10) DEFAULT NULL,
`HCOHCOLinkType` varchar(10) DEFAULT NULL,
PRIMARY KEY (`Relation_Pkey`,`SourceID`,`TargetID`,`RltnPrmryID`),
UNIQUE KEY `Relation_Pkey_UNIQUE` (`Relation_Pkey`),
KEY `idx_STG_RELATION` (`RelationType`,`SrcDataRfrshDt`,`SourceCountry`,`EndDt`),
KEY `Source_ID_idx` (`SourceID`),
KEY `Target_ID_idx` (`TargetID`),
CONSTRAINT `Source_ID` FOREIGN KEY (`SourceID`) REFERENCES `STG_CUSTOMER` (`CustomerID`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `Target_ID` FOREIGN KEY (`TargetID`) REFERENCES `STG_CUSTOMER` (`CustomerID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `STG_RELATION_ROLE` (
`RltnRole_PKey` int(11) NOT NULL AUTO_INCREMENT,
`SourceSystemName` varchar(10) NOT NULL,
`ActivityID` varchar(15) NOT NULL,
`RltnFrgnID` varchar(50) NOT NULL,
`SrcDataRfrshDt` date NOT NULL,
`StartDt` date NOT NULL,
`EndDt` date NOT NULL,
`SourceCountry` varchar(2) NOT NULL,
`HCPHCORoleType` varchar(10) DEFAULT NULL,
`HCPHCORoleField` varchar(10) DEFAULT NULL,
`HCPHCORole` varchar(10) DEFAULT NULL,
`HCPHCORoleStatus` varchar(20) DEFAULT NULL,
PRIMARY KEY (`RltnRole_PKey`,`SourceSystemName`,`ActivityID`,`RltnFrgnID`),
KEY `idx_STG_RELATION_ROLE` (`SrcDataRfrshDt`,`SourceSystemName`,`SourceCountry`,`EndDt`),
KEY `Rltn_Frgn_ID_idx` (`RltnFrgnID`),
CONSTRAINT `RltnFrgnID` FOREIGN KEY (`RltnFrgnID`) REFERENCES `STG_RELATION` (`RltnPrmryID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The Table RELATION got created successfully, but whenver I am trying to create the child table (RELATION_ROLE with parent as RELATION), the table creation is failing with the
Error 1215: Cannot Add Foreign Key Constraint
error message.
Am I missing something here?
Please note that CUSTOMER is the main table with child as RELATION (Customer_ID acting as Primary and Foreign Key) which further has a child RELATION_ROLE (RltnPrmryID is the Primary Key while RltnFrgnID is the foreign key.
Please help me to get the issue resolved.
Uh, there are quite a few problems there - in particular with your table designs.
First of all, the STG_RELATION.RltnPrmryID is not the left most field of any indexes. MySQL requires both endpoints of a foreign key to be the leftmost fields of an index. The leftmost fields are the ones that can be used for lookups. This is the direct reason of the error.
Secondly, the primary key of STG_RELATION table is a mess. The child table should reference the primary key or a unique key from the parent table. STG_RELATION.RltnPrmryID is neither, it is only part of the primary key. Relation_Pkey field being auto increment already uniquely identifies records within the STG_RELATION table, therefore this should be the PK and STG_RELATION_ROLE table should reference this column in the foreign key (obviously, you need to adjust the field type for this to work in STG_RELATION_ROLE). Indexes on integers are a lot more efficient than indexes on strings from a performance point of view.

Mysql Percona crushes the table while trying to create a unique index on fields where there is a generated one

CREATE TABLE tasks (
`user_id` INT(10) UNSIGNED NOT NULL,
`name` VARCHAR(255) NOT NULL,
`code` VARCHAR(255) NOT NULL,
`params` JSON,
`hash` VARCHAR(32) GENERATED ALWAYS AS (MD5(`params`)),
`created_at` TIMESTAMP NULL DEFAULT NULL,
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
CONSTRAINT `tasks_user_id_users_id_fk`
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
then i try to add a unique index on user_id and hash, i tried to do it during the table create, but there were a problem with the foreign key, so i decided to do it separately.
ALTER TABLE tasks
ADD UNIQUE INDEX `tasks_user_id_hash_unique_idx` (`user_id`, `hash`);
Then i get strange problem error 1146
Table '<dbname>.tasks' doesn't exist
Since then strange errors
1. I cannot delete it while it exists and i cannot do with it anything, cause it does not exist. After mysql reload I get the table deleted but if i try to create it again:
Error Code: 1813
Tablespace '<dbname>.tasks' exists.
I found the decision for unique field, i simply genereate md5( hash + user_id) UNIQUE. But How can I get rid of that problem which still exists and what is going on. It looks like a BUG in mysql Percona 5.7.14-7
so the right way to create the table
CREATE TABLE tasks (
`user_id` INT(10) UNSIGNED NOT NULL,
`name` VARCHAR(255) NOT NULL,
`code` VARCHAR(255) NOT NULL,
`params` JSON,
`hash` VARCHAR(32) GENERATED ALWAYS AS (MD5(CONCAT(`params`,`user_id`))) UNIQUE,
`created_at` TIMESTAMP NULL DEFAULT NULL,
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
CONSTRAINT `tasks_user_id_users_id_fk`
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
But, again, the question with the ghosts still exists after the first tries!

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.