Cannot create foreign key to different database in mysql - mysql

I have two tables on different databases in mysql. I'm trying to create a composite foreign key from one table to the other and for some reason it doesn't work. It only works if I use a single primary key field instead of a composite key.
The problematic constraint in the example below is fk_dummy_table11. I get Error Code: 1215. Cannot add foreign key constraint when executing the statement.
Create table statement for "dummy" in DB NREAP:
CREATE TABLE IF NOT EXISTS `NREAP`.`dummy` (
`id` INT NOT NULL,
`table1_TDO_COD_TIP_DOC` VARCHAR(14) NOT NULL,
`table1_RFI_NUM_DOC` INT NOT NULL,
`table1_RFI_VER_DOC` INT NOT NULL,
`table1_RFI_NOM_FIC` VARCHAR(128) NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_dummy_table11_idx` (`table1_TDO_COD_TIP_DOC` ASC, `table1_RFI_NUM_DOC` ASC, `table1_RFI_VER_DOC` ASC, `table1_RFI_NOM_FIC` ASC),
CONSTRAINT `fk_dummy_table11`
FOREIGN KEY (`table1_TDO_COD_TIP_DOC` , `table1_RFI_NUM_DOC` , `table1_RFI_VER_DOC` , `table1_RFI_NOM_FIC`)
REFERENCES `TRANS`.`table1` (`TDO_COD_TIP_DOC` , `RFI_NUM_DOC` , `RFI_VER_DOC` , `RFI_NOM_FIC`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Create table statement for "table1" in DB TRANS:
CREATE TABLE IF NOT EXISTS `TRANS`.`table1` (
`TDO_COD_TIP_DOC` VARCHAR(14) NOT NULL,
`RFI_NUM_DOC` INT NOT NULL,
`RFI_VER_DOC` INT NOT NULL,
`RFI_NOM_FIC` VARCHAR(128) NOT NULL,
`RFI_LOC_FIC` VARCHAR(1000) NULL,
`RFI_DES_FIC` VARCHAR(255) NULL,
`RFI_TIPO` VARCHAR(100) NOT NULL,
`DAT_ALT` DATE NOT NULL,
`COD_UTI_ALT` VARCHAR(14) NOT NULL,
`DFI_VER_DOC` INT NULL,
`DFI_NUM_SEQ` INT NULL,
`CAM_ANO_INI_CAM` VARCHAR(4) NULL,
PRIMARY KEY (`TDO_COD_TIP_DOC`, `RFI_NUM_DOC`, `RFI_VER_DOC`, `RFI_NOM_FIC`))
ENGINE = InnoDB;
Please help, this is so frustrating...
Edit1 - I'm running mysql version 5.7.12
Edit2 - I've ran the SHOW ENGINE INNODB STATUS command, it gives me the following output:
I'm running mysql version 5.7.12, it's the latest one I think.
I've ran innodb status:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2016-07-13 10:28:34 0x124c Error in foreign key constraint of table nreap/dummy:
FOREIGN KEY (`table1_TDO_COD_TIP_DOC` , `table1_RFI_NUM_DOC` , `table1_RFI_VER_DOC` , `table1_RFI_NOM_FIC`)
REFERENCES `TRANS`.`table1` (`TDO_COD_TIP_DOC` , `RFI_NUM_DOC` , `RFI_VER_DOC` , `RFI_NOM_FIC`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB:
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.

I've eventually figured out the problem.
I've narrowed it down to a problem in using VARCHAR keys, the restraint worked fine with other datatypes. After a few experiments I've added a specific charset for each schema and it worked. Adding the specific charset to each table also works.
Thanks for the help!

Related

how to fix Error in EER diagram to create tables?

when I wanted to generate tables, I got this error I don't know how to fix it. Is anyone face to this problem and how you solve it?
thanks
CREATE TABLE IF NOT EXISTS `tb_inv_detail` (
`inv_id_fk` INT UNSIGNED NOT NULL,
`part_id_fk` INT UNSIGNED NOT NULL,
`qty` DECIMAL(12,2) NOT NULL,
`tb_detailed` VARCHAR(50) NULL,
`tb_inv_detailcol` VARCHAR(45) NULL,
PRIMARY KEY (`inv_id_fk`),
INDEX `fk_tb_inv_detail_tb_parts1_idx` (`part_id_fk` ASC) VISIBLE,
CONSTRAINT `fk_tb_inv_detail_tb_parts1`
FOREIGN KEY (`part_id_fk`)
REFERENCES `tb_parts` (`part_id_pk`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_tb_inv_detail_tb_invoice1`
FOREIGN KEY (`inv_id_fk`)
REFERENCES `tb_invoice` (`inv_id_pk`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
SQL script execution finished: statements: 25 succeeded, 1 failed
Also this screenshot of my EER diagram:
Well the obvious code which is missing from what you posted above is the DDL for the two tables referred to by the foreign keys defined in tb_inv_detail. These tables are:
tb_parts
tb_invoice
These tables must be defined first, with correctly named primary key columns to match the foreign keys in your table above.
CREATE TABLE tb_parts (
part_id_pk INT UNSIGNED NOT NULL,
PRIMARY KEY (part_id_pk), -- referred to by part_id_fk
...
)
CREATE TABLE tb_invoice (
inv_id_pk INT UNSIGNED NOT NULL,
PRIMARY KEY (inv_id_pk), -- referred to by inv_id_fk
...
)

MySQL Foreign key constraint are incompatible

MySQL Version 8.0.17
The full error reads:
Referencing column 'groupLineId' and referenced column 'groupLineId' in foreign key constraint 'salesItemLine-groupLine' are incompatible
I am trying to link two tables via the groupLineId which are both NOT NULL VARCHAR(12). I am not sure why I am getting the error. I have several other foreign key relationships like this in my DB.
I am using the following code to generate the two tables. (Note: code for invoice table not shown)
CREATE TABLE IF NOT EXISTS `reports`.`groupLine` (
`groupLineId` VARCHAR(12) NOT NULL,
`lineNum` INT NOT NULL,
`invoiceId` VARCHAR(12) NOT NULL,
PRIMARY KEY (`groupLineId`, `lineNum`, `invoiceId`),
INDEX `groupLine-invoice_idx` (`invoiceId` ASC) VISIBLE,
CONSTRAINT `groupLine-invoice`
FOREIGN KEY (`invoiceId`)
REFERENCES `reports`.`invoice` (`invoiceId`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `reports`.`salesItemLine` (
`groupLineId` VARCHAR(12) NOT NULL,
`lineNum` INT NOT NULL,
`description` VARCHAR(256) NULL,
`amount` DECIMAL NULL,
`detailType` VARCHAR(45) NULL,
PRIMARY KEY (`groupLineId`, `lineNum`),
INDEX `salesItemLine-groupLine_idx` (`groupLineId` ASC) VISIBLE,
CONSTRAINT `salesItemLine-groupLine`
FOREIGN KEY (`groupLineId`)
REFERENCES `reports`.`groupLine` (`groupLineId`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
If anyone comes across this my problem was how I was making changes and using the "Forward Engineer" feature of MySQL Workbench. I had originally created the database with groupLineId ID as type INT. I then changed the model to make the groupLineId in both tables to VARCHAR(12). Then when I would run "Forward Engineer" it would first write the new groupLine table and change the type of groupLineId to VARCHAR(12) this would then break the existing FROGIEN key with salesItemLine table which has not been updated and still has the type of groupeLineId as INT.
The solution was to DROP both tables before rerunning the forward engineering. (Or at least manually dropping the existing constraints)

why i Cannot add foreign key constraint in MySQL Workbench

i have customer table with nid_c,nama_customer, and more field ..
second table I have kendaraan with nopol,nid_c,nama_customer, and more field ..
I try make relation between this table..
I want update data nid_c and nama_customer on kendaraan table when I update customer table.
I got error message here.
Executing SQL script in server
ERROR: Error 1215: Cannot add foreign key constraint
SQL Code:
-- -----------------------------------------------------
-- Table `BengkelBiru`.`kendaraan`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `BengkelBiru`.`kendaraan` (
`NOPOL` VARCHAR(12) NOT NULL,
`NID_C` VARCHAR(7) NULL DEFAULT NULL,
`NAMA_CUSTOMER` VARCHAR(25) NULL DEFAULT NULL,
`MERK` VARCHAR(15) NULL DEFAULT NULL,
`TYPE` VARCHAR(25) NULL DEFAULT NULL,
`CC` VARCHAR(4) NULL DEFAULT NULL,
`TAHUN` VARCHAR(4) NULL DEFAULT NULL,
`WARNA` VARCHAR(10) NULL DEFAULT NULL,
`STATUS` VARCHAR(7) NULL DEFAULT NULL,
PRIMARY KEY (`NOPOL`),
INDEX `pkk_idx` (`NAMA_CUSTOMER` ASC, `NID_C` ASC),
CONSTRAINT `FK_NID_C`
FOREIGN KEY (`NAMA_CUSTOMER` , `NID_C`)
REFERENCES `BengkelBiru`.`customer` (`NID_C` , `NID_C`)
ON DELETE NO ACTION
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
SQL script execution finished: statements: 14 succeeded, 1 failed
Fetching back view definitions in final form.
Nothing to fetch
Your problem is on one or both of these lines:
FOREIGN KEY (`NAMA_CUSTOMER` , `NID_C`)
REFERENCES `BengkelBiru`.`customer` (`NID_C` , `NID_C`)
^^^^^^^ Looks wrong s/b NAMA_CUSTOMER
I think you want this line:
REFERENCES `BengkelBiru`.`customer` (`NID_C` , `NID_C`)
to be
REFERENCES `BengkelBiru`.`customer` (`NAMA_CUSTOMER`, `NID_C`)
Why are you referring to NID_C twice in the reference? I say this because you define the foreign key as:
FOREIGN KEY (`NAMA_CUSTOMER` , `NID_C`)
and your descriptions at the top shows customer having NID_C and NAMA_CUSTOMER as columns.
However, fundamentally, why do you have Nama_customer in the kendaraan (vehicle) table at all? This doesn't seem to be 3rd normal form. You've repeated the customer name in a second table; which isn't part of the Customer's PK. Now, this may be acceptable if you want to keep the name of the customer at the time the entry is made into kendaraan; but since you're making it part of the FK... and doing cascade update/delete... it's very odd.
So maybe you just want:
FOREIGN KEY (`NID_C`)
REFERENCES `BengkelBiru`.`customer` (`NID_C`)
Assuming the Primary Key of Customer is NID_C
I dont think you can declare both at the same time. Try doing them separately.
CONSTRAINT `FK_NAMA_CUSTOMER`
FOREIGN KEY (`NAMA_CUSTOMER`)
REFERENCES `BengkelBiru`.`customer` (`NID_C`)
CONSTRAINT `FK_NID_C`
FOREIGN KEY (`NID_C`)
REFERENCES `BengkelBiru`.`customer` (`NID_C`)
There could be any possible scenario :-
1.Columns in the parent tables Can be INT UNSIGNED?
2.Data type in both tables should be same.
3.You are trying to reference a nonexistent key on the target table. Make sure that it is a key on the other table (it can be a primary or unique key).
Foregin Key Constaints

Mysql error 150 with creating a table that has a foreign key constraint

I am getting error 150 on the following create statement:
CREATE TABLE `lazarus`.`warehouses_devices` (
`parent_unit_id` INT UNSIGNED NULL DEFAULT NULL,
`child_unit_id` INT UNSIGNED NULL DEFAULT NULL,
`message_type` VARCHAR(255) NULL,
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`value` LONGTEXT NOT NULL,
INDEX `parent_unit_id` (`parent_unit_id` ASC),
INDEX `child_unit_id` (`child_unit_id` ASC),
INDEX `message_type` (`message_type` ASC),
INDEX `date` (`date` ASC),
CONSTRAINT `fk_parent_unit_id_unit_id`
FOREIGN KEY (`parent_unit_id`)
REFERENCES `lazarus`.`logs` (`unit_id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
And I am not sure why, I look up error 150 and it states that its foreign key issues and I am really confused as the reason isn't very clear.
The exact error is ERROR 1005: Can't create table 'lazarus.warehouses_devices' (errno: 150)
Considering that you already have a table created called logs
which has unit_id set as primary key. Most probably the error is causing due to datatype mismatch between referred column and referring column.
Then you probably need to check that the column parent_unit_id in warehouses_devices has the same data type as in logs (unit_id).
Make sure both in lazarus.warehouses_devices the parent_unit_id INT UNSIGNED
In logs table as well the unit_id must be INT UNSIGNED
Also, in your CREATE TABLE lazarus.warehouses_devices ( you are creating a constraint named
fk_parent_unit_id_unit_id. make sure you don't have another constraint with the same name already created in some other table.
According to the documentation:
InnoDB does not currently support foreign keys for tables with
user-defined partitioning. This means that no user-partitioned InnoDB
table may contain foreign key references or columns referenced by
foreign keys.
logs is partitioned, while warehouses_devices is not.

MySQL Cannot Add Foreign Key Constraint

So I'm trying to add Foreign Key constraints to my database as a project requirement and it worked the first time or two on different tables, but I have two tables on which I get an error when trying to add the Foreign Key Constraints.
The error message that I get is:
ERROR 1215 (HY000): Cannot add foreign key constraint
This is the SQL I'm using to create the tables, the two offending tables are Patient and Appointment.
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=1;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
CREATE SCHEMA IF NOT EXISTS `doctorsoffice` DEFAULT CHARACTER SET utf8 ;
USE `doctorsoffice` ;
-- -----------------------------------------------------
-- Table `doctorsoffice`.`doctor`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `doctorsoffice`.`doctor` ;
CREATE TABLE IF NOT EXISTS `doctorsoffice`.`doctor` (
`DoctorID` INT(11) NOT NULL AUTO_INCREMENT ,
`FName` VARCHAR(20) NULL DEFAULT NULL ,
`LName` VARCHAR(20) NULL DEFAULT NULL ,
`Gender` VARCHAR(1) NULL DEFAULT NULL ,
`Specialty` VARCHAR(40) NOT NULL DEFAULT 'General Practitioner' ,
UNIQUE INDEX `DoctorID` (`DoctorID` ASC) ,
PRIMARY KEY (`DoctorID`) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `doctorsoffice`.`medicalhistory`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `doctorsoffice`.`medicalhistory` ;
CREATE TABLE IF NOT EXISTS `doctorsoffice`.`medicalhistory` (
`MedicalHistoryID` INT(11) NOT NULL AUTO_INCREMENT ,
`Allergies` TEXT NULL DEFAULT NULL ,
`Medications` TEXT NULL DEFAULT NULL ,
`ExistingConditions` TEXT NULL DEFAULT NULL ,
`Misc` TEXT NULL DEFAULT NULL ,
UNIQUE INDEX `MedicalHistoryID` (`MedicalHistoryID` ASC) ,
PRIMARY KEY (`MedicalHistoryID`) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `doctorsoffice`.`Patient`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `doctorsoffice`.`Patient` ;
CREATE TABLE IF NOT EXISTS `doctorsoffice`.`Patient` (
`PatientID` INT unsigned NOT NULL AUTO_INCREMENT ,
`FName` VARCHAR(30) NULL ,
`LName` VARCHAR(45) NULL ,
`Gender` CHAR NULL ,
`DOB` DATE NULL ,
`SSN` DOUBLE NULL ,
`MedicalHistory` smallint(5) unsigned NOT NULL,
`PrimaryPhysician` smallint(5) unsigned NOT NULL,
PRIMARY KEY (`PatientID`) ,
UNIQUE INDEX `PatientID_UNIQUE` (`PatientID` ASC) ,
CONSTRAINT `FK_MedicalHistory`
FOREIGN KEY (`MEdicalHistory` )
REFERENCES `doctorsoffice`.`medicalhistory` (`MedicalHistoryID` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `FK_PrimaryPhysician`
FOREIGN KEY (`PrimaryPhysician` )
REFERENCES `doctorsoffice`.`doctor` (`DoctorID` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `doctorsoffice`.`Appointment`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `doctorsoffice`.`Appointment` ;
CREATE TABLE IF NOT EXISTS `doctorsoffice`.`Appointment` (
`AppointmentID` smallint(5) unsigned NOT NULL AUTO_INCREMENT ,
`Date` DATE NULL ,
`Time` TIME NULL ,
`Patient` smallint(5) unsigned NOT NULL,
`Doctor` smallint(5) unsigned NOT NULL,
PRIMARY KEY (`AppointmentID`) ,
UNIQUE INDEX `AppointmentID_UNIQUE` (`AppointmentID` ASC) ,
CONSTRAINT `FK_Patient`
FOREIGN KEY (`Patient` )
REFERENCES `doctorsoffice`.`Patient` (`PatientID` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `FK_Doctor`
FOREIGN KEY (`Doctor` )
REFERENCES `doctorsoffice`.`doctor` (`DoctorID` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `doctorsoffice`.`InsuranceCompany`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `doctorsoffice`.`InsuranceCompany` ;
CREATE TABLE IF NOT EXISTS `doctorsoffice`.`InsuranceCompany` (
`InsuranceID` smallint(5) NOT NULL AUTO_INCREMENT ,
`Name` VARCHAR(50) NULL ,
`Phone` DOUBLE NULL ,
PRIMARY KEY (`InsuranceID`) ,
UNIQUE INDEX `InsuranceID_UNIQUE` (`InsuranceID` ASC) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `doctorsoffice`.`PatientInsurance`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `doctorsoffice`.`PatientInsurance` ;
CREATE TABLE IF NOT EXISTS `doctorsoffice`.`PatientInsurance` (
`PolicyHolder` smallint(5) NOT NULL ,
`InsuranceCompany` smallint(5) NOT NULL ,
`CoPay` INT NOT NULL DEFAULT 5 ,
`PolicyNumber` smallint(5) NOT NULL AUTO_INCREMENT ,
PRIMARY KEY (`PolicyNumber`) ,
UNIQUE INDEX `PolicyNumber_UNIQUE` (`PolicyNumber` ASC) ,
CONSTRAINT `FK_PolicyHolder`
FOREIGN KEY (`PolicyHolder` )
REFERENCES `doctorsoffice`.`Patient` (`PatientID` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `FK_InsuranceCompany`
FOREIGN KEY (`InsuranceCompany` )
REFERENCES `doctorsoffice`.`InsuranceCompany` (`InsuranceID` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
USE `doctorsoffice` ;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
To find the specific error run this:
SHOW ENGINE INNODB STATUS;
And look in the LATEST FOREIGN KEY ERROR section.
The data type for the child column must match the parent column exactly. For example, since medicalhistory.MedicalHistoryID is an INT, Patient.MedicalHistory also needs to be an INT, not a SMALLINT.
Also, you should run the query set foreign_key_checks=0 before running the DDL so you can create the tables in an arbitrary order rather than needing to create all parent tables before the relevant child tables.
I had set one field as "Unsigned" and other one not. Once I set both columns to Unsigned it worked.
Engine should be the same e.g. InnoDB
Datatype should be the same, and with same length. e.g. VARCHAR(20)
Collation Columns charset should be the same. e.g. utf8
Watchout: Even if your tables have same Collation, columns still could have different one.
Unique - Foreign key should refer to field that is unique (usually primary key) in the reference table.
Try to use the same type of your primary keys - int(11) - on the foreign keys - smallint(5) - as well.
Hope it helps!
Confirm that the character encoding and collation for the two tables is the same.
In my own case, one of the tables was using utf8 and the other was using latin1.
I had another case where the encoding was the same but the collation different. One utf8_general_ci the other utf8_unicode_ci
You can run this command to set the encoding and collation for a table.
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
I hope this helps someone.
To set a FOREIGN KEY in Table B you must set a KEY in the table A.
In table A:
INDEX id (id)
And then in the table B,
CONSTRAINT `FK_id` FOREIGN KEY (`id`) REFERENCES `table-A` (`id`)
I had same problem and the solution was very simple.
Solution : foreign keys declared in table should not set to be not null.
reference : If you specify a SET NULL action, make sure that you have not declared the columns in the child table as NOT NULL. (ref
)
Check following rules :
First checks whether names are given right for table names
Second right data type give to foreign key ?
Please ensure that both the tables are in InnoDB format. Even if one is in MyISAM format, then, foreign key constraint wont work.
Also, another thing is that, both the fields should be of the same type. If one is INT, then the other should also be INT. If one is VARCHAR, the other should also be VARCHAR, etc.
I faced the issue and was able to resolve it by making sure that the data types were exactly matching .
I was using SequelPro for adding the constraint and it was making the primary key as unsigned by default .
Check the signing on both your table columns. If the referring table column is SIGNED, the referenced table column should be SIGNED too.
My problem was that I was trying to create the relation table before other tables!
So you have two ways to fix it:
change the order of MSQL commands
run this before your queries:
SET foreign_key_checks = 0;
NOTE: The following tables were taken from some site when I was doing
some R&D on the database. So the naming convention is not proper.
For me, the problem was, my parent table had the different character set than that of the one which I was creating.
Parent Table (PRODUCTS)
products | CREATE TABLE `products` (
`productCode` varchar(15) NOT NULL,
`productName` varchar(70) NOT NULL,
`productLine` varchar(50) NOT NULL,
`productScale` varchar(10) NOT NULL,
`productVendor` varchar(50) NOT NULL,
`productDescription` text NOT NULL,
`quantityInStock` smallint(6) NOT NULL,
`buyPrice` decimal(10,2) NOT NULL,
`msrp` decimal(10,2) NOT NULL,
PRIMARY KEY (`productCode`),
KEY `productLine` (`productLine`),
CONSTRAINT `products_ibfk_1` FOREIGN KEY (`productLine`) REFERENCES `productlines` (`productLine`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Child Table which had a problem (PRICE_LOGS)
price_logs | CREATE TABLE `price_logs` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`productCode` varchar(15) DEFAULT NULL,
`old_price` decimal(20,2) NOT NULL,
`new_price` decimal(20,2) NOT NULL,
`added_on` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `productCode` (`productCode`),
CONSTRAINT `price_logs_ibfk_1` FOREIGN KEY (`productCode`) REFERENCES `products` (`productCode`) ON DELETE CASCADE ON UPDATE CASCADE
);
MODIFIED TO
price_logs | CREATE TABLE `price_logs` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`productCode` varchar(15) DEFAULT NULL,
`old_price` decimal(20,2) NOT NULL,
`new_price` decimal(20,2) NOT NULL,
`added_on` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `productCode` (`productCode`),
CONSTRAINT `price_logs_ibfk_1` FOREIGN KEY (`productCode`) REFERENCES `products` (`productCode`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
One additional cause of this error is when your tables or columns contain reserved keywords:
Sometimes one does forget these.
If you are getting this error with PhpMyAdmin, disable foreign key checks before importing the SQL file.
For me the target table was blocking the foreign key.
I had to set Auto-Increment (AI) on the table the Foreign-Key was pointing to.
I had a similar error in creating foreign key in a Many to Many table where the primary key consisted of 2 foreign keys and another normal column. I fixed the issue by correcting the referenced table name i.e. company, as shown in the corrected code below:
create table company_life_cycle__history -- (M-M)
(
company_life_cycle_id tinyint unsigned not null,
Foreign Key (company_life_cycle_id) references company_life_cycle(id) ON DELETE CASCADE ON UPDATE CASCADE,
company_id MEDIUMINT unsigned not null,
Foreign Key (company_id) references company(id) ON DELETE CASCADE ON UPDATE CASCADE,
activity_on date NOT NULL,
PRIMARY KEY pk_company_life_cycle_history (company_life_cycle_id, company_id,activity_on),
created_on datetime DEFAULT NULL,
updated_on datetime DEFAULT NULL,
created_by varchar(50) DEFAULT NULL,
updated_by varchar(50) DEFAULT NULL
);
I had similar error with two foreign keys for different tables but with same key names! I have renamed keys and the error had gone)
Had a similar error, but in my case I was missing to declare the pk as auto_increment.
Just in case it could be helpful to anyone
I got the same error. The cause in my case was:
I created a backup of a database via phpmyadmin by copying the whole database.
I created a new db with the same name the old db had und selected it.
I started an SQL script to create updated tables and data.
I got the error. Also when I disabled foreign_key_checks. Altough the database was completely empty.
The cause was: Since i used phpmyadmin to create some foreign keys in the renamed database - the foreign keys where created with a database name prefix but the database name prefix was not updated. So there were still references in the backup-db pointing to the newly created db.
My solution is maybe a little embarrassing and tells the tale of why you should sometimes look at what you have in front of you instead of these posts :)
I had ran a forward engineer before, which failed, so that meant that my database already had a few tables, then i have been sitting trying to fix foreign key contraints failures trying to make sure that everything was perfect, but it ran up against the tables previously created, so it was to no prevail.
In my case, there was a syntax error which was not explicitly notified by MySQL console upon running the query. However, SHOW ENGINE INNODB STATUS command's LATEST FOREIGN KEY ERROR section reported,
Syntax error close to:
REFERENCES`role`(`id`) ON DELETE CASCADE) ENGINE = InnoDB DEFAULT CHARSET = utf8
I had to leave a whitespace between REFERENCES and role to make it work.
For me it was - you can't omit prefixing the current DB table if you create a FK for a non-current DB referencing the current DB:
USE currrent_db;
ALTER TABLE other_db.tasks ADD CONSTRAINT tasks_fk FOREIGN KEY (user_id) REFERENCES currrent_db.users (id);
If I omit "currrent_db." for users table, I get the FK error. Interesting that SHOW ENGINE INNODB STATUS; shows nothing in this case.
My Solution!!
If we want to have column1 of table1 as a foreign key of table2, then column1 should be a key of table1.
For example, consider we have departments table, which has dept_id column.
Now let's say we have another table named employees which has emp_dept_id column.
If we want to use the dept_id column of the department table as a foreign key for the emp_dept_id column of emp, then the dept_id of department table SHOULD ATLEAST BE a key if not a primary key.
So make sure that dept_id of depratment is either a primary key or a unique key before using it as a foreign key for another table.
I had this same issue then i corrected the Engine name as Innodb in both parent and child tables and corrected the reference field name
FOREIGN KEY (c_id) REFERENCES x9o_parent_table(c_id)
then it works fine and the tables are installed correctly. This will be use full for someone.