Tables are empty set in MySQL - mysql

I used MySQL Workbench to generate a database and now I inserted it into the command-line client using:
mysql> . C:\Documents and
Settings\kdegroote\My
Documents\School\2008-2009\ICT2
\Gegevensbanken\Labo\Hoofdstuk 3 oef
6\pizzasecondtry.sql
For some reason, the last table won't be accepted. "Cannot create table" is the error message.
I manually editted the data to basically be the same, just without the special options Workbench adds to it and it worked like that.
I've been studying the original but I don't understand why it won't show me the tables.
So I was wondering if anybody here could have a look at it. Maybe someone else will see what I'm overlooking.
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL';
CREATE SCHEMA IF NOT EXISTS `PizzaDelivery` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `PizzaDelivery`;
CREATE TABLE IF NOT EXISTS `PizzaDelivery`.`Visitors` (
`visitor_id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(45) NOT NULL ,
`adres` VARCHAR(45) NOT NULL ,
`telephone` MEDIUMBLOB NOT NULL ,
`email` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`visitor_id`))ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `PizzaDelivery`.`Employees` (
`employee_id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`employee_id`))ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `PizzaDelivery`.`Orders` (
`order_id` INT NOT NULL AUTO_INCREMENT ,
`pizza` VARCHAR(45) NOT NULL ,
`extra` VARCHAR(45) NULL ,
`kind` VARCHAR(45) NOT NULL ,
`amount` VARCHAR(45) NOT NULL ,
`visitor_id` INT NOT NULL ,
`employee_id` INT NOT NULL ,
`order_time` TIME NOT NULL ,
PRIMARY KEY (`order_id`) ,
INDEX `visitor_id` (`visitor_id` ASC) ,
INDEX `employee_id` (`employee_id` ASC) ,
CONSTRAINT `visitor_id`
FOREIGN KEY (`visitor_id` )
REFERENCES `PizzaDelivery`.`Visitors` (`visitor_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `employee_id`
FOREIGN KEY (`employee_id` )
REFERENCES `PizzaDelivery`.`Employees` (`employee_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `PizzaDelivery`.`Deliveries` (
`employee_id` INT NOT NULL ,
`order_id` INT NOT NULL ,
`voertuig_id` INT NOT NULL ,
`deliverytime` TIME NOT NULL ,
PRIMARY KEY (`employee_id`, `order_id`) ,
INDEX `employee_id` (`employee_id` ASC) ,
INDEX `order_id` (`order_id` ASC) ,
CONSTRAINT `employee_id`
FOREIGN KEY (`employee_id` )
REFERENCES `PizzaDelivery`.`Employees` (`employee_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `order_id`
FOREIGN KEY (`order_id` )
REFERENCES `PizzaDelivery`.`Orders` (`order_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)ENGINE=InnoDB;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;

You can often get more information from an InnoDB error like this:
mysql> SHOW ENGINE INNODB STATUS;
The output is long, but among the status output I saw this:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
081221 12:02:36 Error in foreign key constraint creation
for table `pizzadelivery/deliveries`.
A foreign key constraint of name `pizzadelivery/employee_id`
already exists.
The problem is that the Deliveries and the Orders tables both declare a foreign key constraint named employee_id.
Constraint names must be unique across all tables in a given database. The "errno: 121" is an InnoDB error code indicating a duplicate key error. In this case, the uniqueness of constraint names is not satisfied.
You can fix this problem and still keep your foreign key constraints if you just change the name of the declared constraint, for example:
CREATE TABLE IF NOT EXISTS `PizzaDelivery`.`Deliveries` (
. . .
CONSTRAINT `employee_id2`
FOREIGN KEY (`employee_id` )
. . .

PROBLEM SOLVED.
I solved my problem here rather by accident.
The problem appeared to be the constraints in the "Deliveries" table.
The 2 primairy keys are foreign keys at the same time and that generates and error if you want to constrain them.
So I simply left out the constraints and everything works.

Try use PizzaDelivery before running show tables. You created your tables in the PizzaDelivery schema, but you probably connected with a different default schema. The default schema is the parameter to the mysql command line client:
$ mysql -h <db-host> -u <username> -p <schema-name>
(note: -p means prompt for password when it is not given an argument, which you generally shouldn't do because arguments show up in ps output and also get saved to disk in shell history. All of the command line parameters are optional.)

Related

cannot add foreign key constraint in phpmyadmin

While creating 2 tables in phpmyadmin I am getting an error like this.
MySQL said: Documentation
#1215 - Cannot add foreign key constraint
My table structures are
CREATE TABLE `iwd_storelocator_manufacturer` (
`entity_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` varchar(255) NOT NULL ,
`code` varchar(255) NOT NULL ,
`grayscale_image` varchar(255) NULL ,
`color_image` varchar(255) NULL ,
PRIMARY KEY (`entity_id`)
);
CREATE TABLE `iwd_storelocator_manufacturer_to_store` (
`manufacturer_id` int(11) UNSIGNED NOT NULL ,
`store_id` int(11) NOT NULL ,
`preferred` int NULL ,
PRIMARY KEY (`manufacturer_id`, `store_id`),
FOREIGN KEY (`store_id`) REFERENCES `iwd_storelocator_store` (`store_id`) ON DELETE RESTRICT ON UPDATE CASCADE,
FOREIGN KEY (`manufacturer_id`) REFERENCES `iwd_storelocator_manufacturer` (`entity_id`) ON DELETE RESTRICT ON UPDATE CASCADE
);
Can you tell me whats the problem in it?
This is my iwd_storelocator_store table
iwd_storelocator_store
In order to know exactly what is wrong, you must check in LATEST FOREIGN KEY ERROR section.
Use this query to find this out:
SHOW ENGINE INNODB STATUS
Also, make sure that all the data types are the same: the data type of the child column must match the data type from the parent column.
If the problem is the order of creation of the tables (which can cause this error), just run set foreign_key_checks=0 so you can create the tables in any order rather than having to create all the parents tables BEFORE the child tables.
Finally, make sure that the encoding is the same for all the tables.
EDIT: in your case, you should also give us the structure of iwd_storelocator_store table
Now that we have your iwd_storelocator_store table, I think that you should create an index on store_id column as it is not the primary key of the table

Cannot create foreign key to different database in 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!

Error 1215: Cannot add foreign key constraint

I built a database with mySql Workbench, but when I try to forward engineer my model to the server, I get the following error :
ERROR: Error 1215: Cannot add foreign key constraint
followed by the definition of the table where the foreign key is defined, salaire_annee_ca
I read similar topics to identify the usual causes for this error, and checked :
if the foreign key defined in salaire_annee_ca references the primary key of another table, which it does
if something in the code allowed my key to be null, which it doesn't
if the types of the reference and of the foreign key were the same
It seems to me that all these conditions are ok, so I don't understand why I still get that message. Here are the definitions of my tables :
These are the two main ones :
-- Table `credit_impot_db`.`salaires_annee`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `credit_impot_db`.`salaires_annee` (
`salaire_annee_id` INT(11) NOT NULL ,
`salaire_annuel` DOUBLE NOT NULL DEFAULT 0 ,
`heures_travaillees` DOUBLE NOT NULL DEFAULT 0 ,
`pourcentage_rsde` DOUBLE NOT NULL DEFAULT 0 ,
`jours_travailles` INT(3) NOT NULL DEFAULT 0 ,
PRIMARY KEY (`salaire_annee_id`) ,
CONSTRAINT `salaire_annee_id`
FOREIGN KEY (`salaire_annee_id` )
REFERENCES `credit_impot_db`.`employes_ac` (`employe_ac_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
This one is at the origin of the message :
-- -----------------------------------------------------
-- Table `credit_impot_db`.`salaire_annee_ca`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `credit_impot_db`.`salaire_annee_ca` (
`salaire_annee_ca_id` INT(11) NOT NULL ,
PRIMARY KEY (`salaire_annee_ca_id`) ,
CONSTRAINT `salaire_annee_ca_id`
FOREIGN KEY (`salaire_annee_ca_id` )
REFERENCES `credit_impot_db`.`salaires_annee` (`salaire_annee_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
And the following two are also referenced :
-- -----------------------------------------------------
-- Table `credit_impot_db`.`employes`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `credit_impot_db`.`employes` (
`employe_id` INT(11) NOT NULL AUTO_INCREMENT ,
`employe_nom` VARCHAR(255) NOT NULL ,
`employe_prenom` VARCHAR(255) NOT NULL ,
`employe_fonction` VARCHAR(255) NULL ,
`employe_experience` VARCHAR(255) NULL DEFAULT NULL ,
PRIMARY KEY (`employe_id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `credit_impot_db`.`employes_ac`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `credit_impot_db`.`employes_ac` (
`employe_ac_id` INT(11) NOT NULL AUTO_INCREMENT ,
`fk_employe_ac_employe_id` INT(11) NULL ,
`fk_employe_ac_ac_id` INT(11) NULL ,
PRIMARY KEY (`employe_ac_id`) ,
INDEX `fk_employe_ac_employe_id_idx` (`fk_employe_ac_employe_id` ASC) ,
INDEX `fk_employe_ac_ac_id_idx` (`fk_employe_ac_ac_id` ASC) ,
CONSTRAINT `fk_employe_ac_employe_id`
FOREIGN KEY (`fk_employe_ac_employe_id` )
REFERENCES `credit_impot_db`.`employes` (`employe_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_employe_ac_ac_id`
FOREIGN KEY (`fk_employe_ac_ac_id` )
REFERENCES `credit_impot_db`.`dossier_client` (`ac_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Any help would be appreciated!
I hit the dreaded error 1215 while using the Workbench and spent a long time trying to work out what was wrong. I eventually noticed that some of my tables were defined with "latin1 - default collation", while others were defined with "Schema Default". I had to expand the table definitions one by one in the EER diagram to see the option to change this. I changed all the definitions to "Schema Default" and the problem disappeared. Wow!
Ok I think I figured it out. It seems to be a problem with mySql Workbench, the error disappears if :
I first create my primary key in salaire_annee_ca,
Then Forward engineer my database
Declare my primary key as being a foreign key which references the primary key of salaire_annee
Forward engineer my database again
The error gets resolved:
To create a Foreign key for a table like this
CREATE TABLE users_so
(
username VARCHAR(10) NOT NULL,
password VARCHAR(32) NOT NULL,
enabled SMALLINT,
PRIMARY KEY (username)
);
The below code works fine
CREATE TABLE authorities_so
(
username VARCHAR(10) NOT NULL,
authority VARCHAR(10) NOT NULL,
FOREIGN KEY (username) REFERENCES users_so(username)
);
One of possible cause could be default storage engine on production db.
My problem was similar. I also worked with Workbench, and in local worked perfectly, also worked good in production, until I recreate schema on production server with Forward Engineering.
One of tables become MyISAM instead of InnoDb, and Row format from Don't use become Dynamic.
My solution was:
In Workbench,
Check every table that requires foreign keys to be InnoDb, and
Row format to be Default.

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.

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

I was working on creating some tables in database foo, but every time I end up with errno 150 regarding the foreign key. Firstly, here's my code for creating tables:
CREATE TABLE Clients
(
client_id CHAR(10) NOT NULL ,
client_name CHAR(50) NOT NULL ,
provisional_license_num CHAR(50) NOT NULL ,
client_address CHAR(50) NULL ,
client_city CHAR(50) NULL ,
client_county CHAR(50) NULL ,
client_zip CHAR(10) NULL ,
client_phone INT NULL ,
client_email CHAR(255) NULL ,
client_dob DATETIME NULL ,
test_attempts INT NULL
);
CREATE TABLE Applications
(
application_id CHAR(10) NOT NULL ,
office_id INT NOT NULL ,
client_id CHAR(10) NOT NULL ,
instructor_id CHAR(10) NOT NULL ,
car_id CHAR(10) NOT NULL ,
application_date DATETIME NULL
);
CREATE TABLE Instructors
(
instructor_id CHAR(10) NOT NULL ,
office_id INT NOT NULL ,
instructor_name CHAR(50) NOT NULL ,
instructor_address CHAR(50) NULL ,
instructor_city CHAR(50) NULL ,
instructor_county CHAR(50) NULL ,
instructor_zip CHAR(10) NULL ,
instructor_phone INT NULL ,
instructor_email CHAR(255) NULL ,
instructor_dob DATETIME NULL ,
lessons_given INT NULL
);
CREATE TABLE Cars
(
car_id CHAR(10) NOT NULL ,
office_id INT NOT NULL ,
engine_serial_num CHAR(10) NULL ,
registration_num CHAR(10) NULL ,
car_make CHAR(50) NULL ,
car_model CHAR(50) NULL
);
CREATE TABLE Offices
(
office_id INT NOT NULL ,
office_address CHAR(50) NULL ,
office_city CHAR(50) NULL ,
office_County CHAR(50) NULL ,
office_zip CHAR(10) NULL ,
office_phone INT NULL ,
office_email CHAR(255) NULL
);
CREATE TABLE Lessons
(
lesson_num INT NOT NULL ,
client_id CHAR(10) NOT NULL ,
date DATETIME NOT NULL ,
time DATETIME NOT NULL ,
milegage_used DECIMAL(5, 2) NULL ,
progress CHAR(50) NULL
);
CREATE TABLE DrivingTests
(
test_num INT NOT NULL ,
client_id CHAR(10) NOT NULL ,
test_date DATETIME NOT NULL ,
seat_num INT NOT NULL ,
score INT NULL ,
test_notes CHAR(255) NULL
);
ALTER TABLE Clients ADD PRIMARY KEY (client_id);
ALTER TABLE Applications ADD PRIMARY KEY (application_id);
ALTER TABLE Instructors ADD PRIMARY KEY (instructor_id);
ALTER TABLE Offices ADD PRIMARY KEY (office_id);
ALTER TABLE Lessons ADD PRIMARY KEY (lesson_num);
ALTER TABLE DrivingTests ADD PRIMARY KEY (test_num);
ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Offices FOREIGN KEY (office_id) REFERENCES Offices (office_id);
ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Clients FOREIGN KEY (client_id) REFERENCES Clients (client_id);
ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Instructors FOREIGN KEY (instructor_id) REFERENCES Instructors (instructor_id);
ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Cars FOREIGN KEY (car_id) REFERENCES Cars (car_id);
ALTER TABLE Lessons ADD CONSTRAINT FK_Lessons_Clients FOREIGN KEY (client_id) REFERENCES Clients (client_id);
ALTER TABLE Cars ADD CONSTRAINT FK_Cars_Offices FOREIGN KEY (office_id) REFERENCES Offices (office_id);
ALTER TABLE Clients ADD CONSTRAINT FK_DrivingTests_Clients FOREIGN KEY (client_id) REFERENCES Clients (client_id);
These are the errors that I get:
mysql> ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Cars FOREIGN KEY
(car_id) REFERENCES Cars (car_id);
ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)
I ran SHOW ENGINE INNODB STATUS which gives a more detailed error description:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
100509 20:59:49 Error in foreign key constraint of table foo/#sql-12c_4:
FOREIGN KEY (car_id) REFERENCES Cars (car_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.
See http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
------------
I searched around on StackOverflow and elsewhere online - came across a helpful blog post here with pointers on how to resolve this error - but I can't figure out what's going wrong. Any help would be appreciated!
You should make car_id a primary key in cars.
Note: I had the same problem, and it was because the referenced field was in a different collation in the 2 different tables (they had exact same type).
Make sure all your referenced fields have the same type AND the same collation!
Check that BOTH tables have the same ENGINE. For example if you have:
CREATE Table FOO ();
and:
CREATE Table BAR () ENGINE=INNODB;
If you try to create a constraint from table BAR to table FOO, it will not work on certain MySQL versions.
Fix the issue by following:
CREATE Table FOO () ENGINE=INNODB;
Subtle, but this error got me because I forgot to declare a smallint column as unsigned to match the referenced, existing table which was "smallint unsigned." Having one unsigned and one not unsigned caused MySQL to prevent the foreign key from being created on the new table.
id smallint(3) not null
does not match, for the sake of foreign keys,
id smallint(3) unsigned not null
I got this completely worthless and uninformative error when I tried to:
ALTER TABLE `comments` ADD CONSTRAINT FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;
My problem was in my comments table, user_id was defined as:
`user_id` int(10) unsigned NOT NULL
So... in my case, the problem was with the conflict between NOT NULL, and ON DELETE SET NULL.
Also both the tables need to have same character set.
for e.g.
CREATE TABLE1 (
FIELD1 VARCHAR(100) NOT NULL PRIMARY KEY,
FIELD2 VARCHAR(100) NOT NULL
)ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_bin;
to
CREATE TABLE2 (
Field3 varchar(64) NOT NULL PRIMARY KEY,
Field4 varchar(64) NOT NULL,
CONSTRAINT FORIGEN KEY (Field3) REFERENCES TABLE1(FIELD1)
) ENGINE=InnoDB;
Will fail because they have different charsets. This is another subtle failure where mysql returns same error.
I use Ubuntu linux, and in my case the error was caused by incorrect statement syntax (which I found out by typing perror 150 at the terminal, which gives
MySQL error code 150: Foreign key constraint is incorrectly formed
Changing the syntax of the query from
alter table scale add constraint foreign key (year_id) references year.id;
to
alter table scale add constraint foreign key (year_id) references year(id);
fixed it.
The referenced field must be a "Key" in the referenced table, not necessarily a primary key. So the "car_id" should either be a primary key or be defined with NOT NULL and UNIQUE constraints in the "Cars" table.
And moreover, both fields must be of the same type and collation.
I also received this error (for several tables) along with constraint errors and MySQL connecting and disconnecting when attempting to import an entire database (~800 MB). My issue was the result of The MySQL server max allowed packets being too low. To resolve this (on a Mac):
Opened /private/etc/my.conf
Under # The MySQL server, changed max_allowed_packet from 1M to 4M (You may need to experiment with this value.)
Restarted MySQL
The database imported successfully after that.
Note I am running MySQL 5.5.12 for Mac OS X (x86 64 bit).
check to make the field you are referencing to is an exact match with foreign key, in my case one was unsigned and the other was signed so i just changed them to match and this worked
ALTER TABLE customer_information
ADD CONSTRAINT fk_customer_information1
FOREIGN KEY (user_id)
REFERENCES users(id)
ON DELETE CASCADE
ON UPDATE CASCADE
Solved:
Check to make sure Primary_Key and Foreign_Key are exact match with data types.
If one is signed another one unsigned, it will be failed.
Good practice is to make sure both are unsigned int.
I was using a duplicate Foreign Key Name.
Renaming the FK name solved my problem.
Clarification:
Both tables had a constraint called PK1, FK1, etc. Renaming them/making the names unique solved the problem.
The referenced column must be an index of a single column or the first column in multi column index, and the same type and the same collation.
My two tables have the different collations. It can be shown by issuing show table status like table_name and collation can be changed by issuing alter table table_name convert to character set utf8.
all, I solved a problem and wanted to share it:
I had this error <>
The issue was in that in my statement:
alter table system_registro_de_modificacion add foreign key
(usuariomodificador_id) REFERENCES Usuario(id) On delete restrict;
I had incorrectly written the CASING: it works in Windows WAMP, but in Linux MySQL it is more strict with the CASING, so writting "Usuario" instead of "usuario" (exact casing), generated the error, and was corrected simply changing the casing.