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

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?)

Related

MySQL error #1005 errno 150

I can't figure out why I'm getting an error here.
CURRENT TABLES:
CREATE TABLE `Clients` (
`ClientID` varchar(8) NOT NULL,
`Age` varchar(20) NOT NULL,
`Postcode` varchar(6) NOT NULL,
PRIMARY KEY (`ClientID`,`Age`,`Postcode`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `Disclosure` (
`ClientID` varchar(8) NOT NULL,
`Fname` varchar(100) DEFAULT NULL,
`Lname` varchar(100) DEFAULT NULL,
`Email` varchar(100) DEFAULT NULL,
`Postcode` varchar(6) NOT NULL,
`Offender` varchar(45) DEFAULT NULL,
`Location` varchar(100) DEFAULT NULL,
`Age` varchar(20) NOT NULL,
`Support` varchar(45) DEFAULT NULL,
`Disclosure` varchar(1000) DEFAULT NULL,
PRIMARY KEY (`ClientID`,`Postcode`,`Age`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
trying to add foreign key
ALTER TABLE `FYP`.`Disclosure`
ADD CONSTRAINT `client`
FOREIGN KEY (`ClientID` , `Postcode` , `Age`)
REFERENCES `FYP`.`Clients` (`ClientID` , `Postcode` , `Age`)
ON DELETE NO ACTION
ON UPDATE CASCADE;
I've tried using show status to see what the error is but I still cant figure it out.
SHOW ENGINE INNODB STATUS
returns:
------------------------ LATEST FOREIGN KEY ERROR
------------------------ 171102 11:35:10 Error in foreign key constraint of table FYP/#sql-266_33b:
FOREIGN KEY (ClientID , Postcode , Age) REFERENCES
FYP.Clients (ClientID , Postcode , Age) ON DELETE NO
ACTION ON UPDATE 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. See
http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
You need an index on the referenced columns. The order of the columns in an index matter. In the clients table change the primary key to
(`ClientID`,`Postcode`,`Age`)
This should do it
ALTER TABLE clients DROP PRIMARY KEY, ADD PRIMARY KEY (`ClientID`,`Postcode`,`Age`);

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: 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.

MySQL table with a varchar column as foreign key

I am trying to create a table with a varchar column as foreign key but MySql gives me an error while creating the table. My query is like this:
CREATE TABLE network_classes (
id TINYINT(1) UNSIGNED NOT NULL AUTO_INCREMENT,
category VARCHAR(80) NOT NULL,
PRIMARY KEY(id),
KEY `key_1` (`id`,`category`)
)
ENGINE=InnoDB;
CREATE TABLE networks (
id TINYINT(3) UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
category VARCHAR(80) NOT NULL,
director_id TINYINT(3) UNSIGNED NULL,
director_name VARCHAR(100) NULL,
description VARCHAR(1000) NULL,
last_modified TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
user_id SMALLINT UNSIGNED NULL,
PRIMARY KEY(id),
KEY `networks_fk1` (`category`),
CONSTRAINT `networks_fk1` FOREIGN KEY (`category`) REFERENCES `network_classes` (`category`) ON DELETE NO ACTION,
INDEX networks_index2471(name),
INDEX networks_index2472(director_id, director_name)
)
ENGINE=InnoDB;
and I get this error:
[Err] 1215 - Cannot add foreign key constraint
I am using MySQL 5.6.12. How can I rewrite my query to fix it?
You can only have a foreign key referencing a unique field. Modify your network_classes table so that the category field is unique, like below
CREATE TABLE network_classes (
id TINYINT(1) UNSIGNED NOT NULL AUTO_INCREMENT,
category VARCHAR(80) NOT NULL,
PRIMARY KEY(id),
UNIQUE KEY `category_UNIQUE` (`category`),
KEY `key_1` (`id`,`category`)
)
ENGINE=InnoDB;
CREATE TABLE networks (
id TINYINT(3) UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
category VARCHAR(80) NOT NULL,
director_id TINYINT(3) UNSIGNED NULL,
director_name VARCHAR(100) NULL,
description VARCHAR(1000) NULL,
last_modified TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
user_id SMALLINT UNSIGNED NULL,
PRIMARY KEY(id),
KEY `networks_fk1` (`category`),
CONSTRAINT `networks_fk1` FOREIGN KEY (`category`) REFERENCES `network_classes` (`category`) ON DELETE NO ACTION,
INDEX networks_index2471(name),
INDEX networks_index2472(director_id, director_name)
)
ENGINE=InnoDB;
You should then be able to add the foreign key you want
column types in the table and the referenced table do not match for
constraint
Why 2 varchar columns with same size not match in type? And of course the answer is obvious collation. Turns out that in the new table the column was UTF-8 instead of ASCII as in the referenced table. Changed to ascii and done.
The target of a FOREIGN KEY constraint needs to be indexed. Usually, it is a PRIMARY KEY so this isn't an issue, but in your case it's not (although it's part of a composite key, that's not enough)
Create an index on your network_classes.category field:
CREATE INDEX category_idx ON network_classes(category);
Then re-create your networks table.
For me, it was the charset that was missing. Just providing an example for reference.
CREATE TABLE `client` (
id int NOT NULL,
name varchar(255) NOT NULL,
email varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
created_at datetime NOT NULL,
created_by varchar(50) NOT NULL DEFAULT 'admin',
updated_at datetime NOT NULL,
updated_by varchar(50) NOT NULL DEFAULT 'admin',
PRIMARY KEY (id),
UNIQUE KEY name_UNIQUE (name),
KEY name_idx (name)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
create table `usecase` (`id` int NOT NULL AUTO_INCREMENT, `client` varchar(255) NOT NULL, `name` varchar(255), `description` varchar(1000), `rule_file` varchar(255), `parsed_rule_file` varchar(255), `archived` BOOLEAN DEFAULT 0, `state` ENUM('INITIATED','PARSED','UPLOADED', 'COMPLETE','FAILED'), `digest` varchar(255), `created_by` varchar(128) DEFAULT NULL, `created_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), `updated_by` varchar(128) DEFAULT NULL, `updated_at` datetime(3) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `uniq_usecase_id` (`client`,`name`), FOREIGN KEY (`client`) REFERENCES client(`name`))ENGINE=InnoDB DEFAULT CHARSET=latin1;
I had missed the line
DEFAULT CHARSET=latin1
in
CONSTRAINT `networks_fk1` FOREIGN KEY (`category`)
REFERENCES `network_classess` (`category`) ON DELETE NO ACTION,
you have used network_classess instead of network_classes (as in your create table script), so that table not exists.
EDIT
Name of your constraint is the same of key (networks_fk1) change ones.
I read better your DDL.
Your table network_classes has a primary key ID, so is correct put as foreign key a field to link your id field, the category field mustn't appear in your table network, but I think you must put fk_network_class (as int) linked to id (of network_classes)

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.