Error 1215 Cannot add foreign key constraint - mysql

Table CARGO
DROP TABLE IF EXISTS "hibernatecurso"."cargo";
CREATE TABLE "hibernatecurso"."cargo" (
"idcargo" int(11) NOT NULL DEFAULT '0',
"funcao" varchar(45) DEFAULT NULL,
PRIMARY KEY ("idcargo")
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Table EMPREGADO
DROP TABLE IF EXISTS "hibernatecurso"."empregado";
CREATE TABLE "hibernatecurso"."empregado" (
"idempregado" int(11) NOT NULL DEFAULT '0',
"nome" varchar(45) NOT NULL DEFAULT '',
"cargo" varchar(45) NOT NULL DEFAULT '',
PRIMARY KEY ("idempregado"),
KEY "idx_cargo" ("cargo")
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
create index in empregado
ALTER TABLE `hibernatecurso`.`empregado` ADD INDEX `idx_cargo`(`cargo`);
Create FK in empregado
ALTER TABLE `hibernatecurso`.`empregado` DROP INDEX `idx_cargo`,
ADD INDEX `idx_cargo`(`cargo`),
ADD CONSTRAINT `FK_empregado_cargo` FOREIGN KEY `FK_empregado_cargo` (`cargo`)
REFERENCES `cargo` (`funcao`)
ON DELETE CASCADE
ON UPDATE CASCADE;
in this part....
Error while executing query.
ALTER TABLE `hibernatecurso`.`empregado` DROP INDEX `idx_cargo`,
ADD INDEX `idx_cargo`(`cargo`),
ADD CONSTRAINT `FK_empregado_cargo` FOREIGN KEY `FK_empregado_cargo` (`cargo`)
REFERENCES `cargo` (`funcao`)
ON DELETE CASCADE
ON UPDATE CASCADE;
MySQL Error Number 1215
Cannot add foreign key constraint
What is causing the error?

I maybe have hard time reading, but I don't see any index on cargo.funcao. This is very probably missing:
ALTER TABLE `hibernatecurso`.`cargo` ADD INDEX `idx_funcao`(`funcao`);
InnoDB permits a foreign key to reference any index column or group of columns.
However, in the referenced table, there must be an
index where the referenced columns are listed as the first columns in
the same order.
http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html

I had the same kind of issue and I fixed it by making sure that collation and types matched in both FK and the parent PK.

Related

Drop foreign key MySQL does not exist

I have a table in MySQL like this (this is returned from using show create table user_org_contacts):
CREATE TABLE `user_org_contacts` (
`user_org_contacts_id` int(11) NOT NULL AUTO_INCREMENT,
`from_user_id` int(11) DEFAULT NULL,
`to_org_user_id` int(11) DEFAULT NULL,
`suggested_vacancy_id` int(11) DEFAULT NULL,
`contact_date` datetime NOT NULL,
`message` text,
PRIMARY KEY (`user_org_contacts_id`),
KEY `FK_Reference_53` (`from_user_id`),
KEY `FK_Reference_54` (`to_org_user_id`),
KEY `FK_Reference_55` (`suggested_vacancy_id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=latin1
I have noticed that my FK_Reference_54 is wrong and points to the wrong table. So I would like to change this one by the correct FK.
This is what I tried:
ALTER TABLE `user_org_contacts`
DROP FOREIGN KEY `FK_Reference_54`;
ALTER TABLE `user_org_contacts`
ADD CONSTRAINT `FK_Reference_54`
FOREIGN KEY (`to_org_user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE;
This produces the following error:
1091 - Can't DROP 'FK_Reference_54'; check that column/key exists
The problem is that you are confusing indexes with primary keys.
The keyword KEY is actually showing you indexes while primary keys use the keywords CONSTRAINT ... FOREIGN KEY ...
Example:
CONSTRAINT `FK_name` FOREIGN KEY (`current_field_name`)
REFERENCES `external_table_name` (`external_field_name`) ON DELETE CASCADE ON UPDATE CASCADE
So in your case, if you want to remove your INDEX you just need to call this query
ALTER TABLE `user_org_contacts`
DROP INDEX `FK_Reference_54`;
Next time I suggest you using some UI for mysql like mysql workbench, with that you would have noticed the issue immediatly.
First Try To remove that column
ALTER TABLE tablename DROP COLUMN columname;
Then:
ALTER TABLE tablename ADD columnname datatype.
Or you can try this Modify option like.
ALTER TABLE tablename MODIFY COLUMN columnname datatype;
Hope This will help you.

Dropping foreign Key constraint

I am trying to drop a FOREIGN KEY but it is throwing an error.
**mysql> alter table traveltime drop foreign key travelid;
ERROR 1091 (42000): Can't DROP 'travelid'; check that column/key exists
mysql>**
The column travelid is the foreign key referencing to another table. Here is the output of SHOW CREATE TABLE traveltime;
CREATE TABLE `traveltime` (
`timeid` int(11) DEFAULT NULL,
`travelid` int(11) DEFAULT NULL,
`hour` int(11) DEFAULT NULL,
`minute` int(11) DEFAULT NULL,
KEY `travelid` (`travelid`),
CONSTRAINT `traveltime_ibfk_1` FOREIGN KEY (`travelid`) REFERENCES `travel` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
The column on which the FOREIGN KEY was defined was travelid, but you probably did not specify an identifier for the constraint itself when it was created, and MySQL created one on your behalf: traveltime_ibfk_1.. That's the identifier you need to target in your ALTER statement.
ALTER TABLE traveltime DROP FOREIGN KEY traveltime_ibfk_1
Though it's difficult to visually parse, MySQL's ALTER TABLE docs specify
ALTER [IGNORE] TABLE tbl_name
[alter_specification [, alter_specification] ...]
[partition_options]
alter_specification:
table_options
...
...
DROP FOREIGN KEY fk_symbol
... where fk_symbol is the constraint's identifier name, rather than the column on which it was defined (because it is possible to define multi-column FK's).

MySQL Drop foreign key Error 152

I am trying to drop a number of foreign keys using:
ALTER TABLE `table` DROP FOREIGN KEY `fk_table_users1` , DROP FOREIGN KEY `fk_table_accounts1` , DROP FOREIGN KEY `fk_table_data1` ;
but it returns the error:
Error on rename of './db/table' to './db/#sql2-179c-288289' (errno: 152)
I have run SHOW ENGINE INNODB STATUS which says:
120725 12:38:37 Error in dropping of a foreign key constraint of table db/table,
in SQL command
ALTER TABLE `table` DROP FOREIGN KEY `fk_table_users1` , DROP FOREIGN KEY `fk_table_accounts1` , DROP FOREIGN KEY `fk_table_data1`
Cannot find a constraint with the given id fk_table_users1.
SHOW CREATE TABLE 'table' output:
CREATE TABLE `table` (
`id` int(11) NOT NULL auto_increment,
`data_id` int(11) NOT NULL,
`account_id` int(11) NOT NULL,
`status` enum('pending','complete') NOT NULL default 'pending',
`created_at` datetime NOT NULL,
`created_by` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_orders_users1` (`created_by`),
KEY `fk_orders_data1` (`data_id`),
KEY `fk_orders_accounts1` (`account_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
However when I look at the structure via phpmyadmin it lists the foreign key with the same name. Do I need to do something else before I can drop the foreign keys?
There are no foreign keys. Refer MySQL documentation which says
KEY is normally a synonym for INDEX.
So basically in table you have created indexes, not foreign keys. For Foreign Key info, Click here
You need to temporarily drop the constraint so that you can remove it.
SET FOREIGN_KEY_CHECKS=0;
and then turn them on again after you drop the foreign key:
SET FOREIGN_KEY_CHECKS=1;
first drop foreign key then delete column
alter table 'table name' drop foreign key 'constraint id ;
if you don't know constraint id create database dump in that constraint id is available in dump file ..
then delete column..
The index name and constraint name may not be same. You should delete constraint first using code: ALTER TABLE tablename DROP FOREIGN KEY constraintname

Add Foreign Key to existing table

I want to add a Foreign Key to a table called "katalog".
ALTER TABLE katalog
ADD CONSTRAINT `fk_katalog_sprache`
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL;
When I try to do this, I get this error message:
Error Code: 1005. Can't create table 'mytable.#sql-7fb1_7d3a' (errno: 150)
Error in INNODB Status:
120405 14:02:57 Error in foreign key constraint of table
mytable.#sql-7fb1_7d3a:
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL:
Cannot resolve table name close to:
(`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL
When i use this query it works, but with wrong "on delete" action:
ALTER TABLE `katalog`
ADD FOREIGN KEY (`Sprache` ) REFERENCES `sprache` (`ID` )
Both tables are InnoDB and both fields are "INT(11) not null". I'm using MySQL 5.1.61. Trying to fire this ALTER Query with MySQL Workbench (newest) on a MacBook Pro.
Table Create Statements:
CREATE TABLE `katalog` (
`ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`AnzahlSeiten` int(4) unsigned NOT NULL,
`Sprache` int(11) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `katalogname_uq` (`Name`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC$$
CREATE TABLE `sprache` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Bezeichnung` varchar(45) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `Bezeichnung_UNIQUE` (`Bezeichnung`),
KEY `ix_sprache_id` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
To add a foreign key (grade_id) to an existing table (users), follow the following steps:
ALTER TABLE users ADD grade_id SMALLINT UNSIGNED NOT NULL DEFAULT 0;
ALTER TABLE users ADD CONSTRAINT fk_grade_id FOREIGN KEY (grade_id) REFERENCES grades(id);
Simply use this query, I have tried it as per my scenario and it works well
ALTER TABLE katalog ADD FOREIGN KEY (`Sprache`) REFERENCES Sprache(`ID`);
Simple Steps...
ALTER TABLE t_name1 ADD FOREIGN KEY (column_name) REFERENCES t_name2(column_name)
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL;
But your table has:
CREATE TABLE `katalog` (
`Sprache` int(11) NOT NULL,
It cant set the column Sprache to NULL because it is defined as NOT NULL.
check this link. It has helped me with errno 150:
http://verysimple.com/2006/10/22/mysql-error-number-1005-cant-create-table-mydbsql-328_45frm-errno-150/
On the top of my head two things come to mind.
Is your foreign key index a unique name in the whole database (#3 in the list)?
Are you trying to set the table PK to NULL on update (#5 in the list)?
I'm guessing the problem is with the set NULL on update (if my brains aren't on backwards today as they so often are...).
Edit: I missed the comments on your original post. Unsigned/not unsigned int columns maybe resolved your case. Hope my link helps someone in the future thought.
How to fix Error Code: 1005. Can't create table 'mytable.#sql-7fb1_7d3a' (errno: 150) in mysql.
alter your table and add an index to it..
ALTER TABLE users ADD INDEX index_name (index_column)
Now add the constraint
ALTER TABLE foreign_key_table
ADD CONSTRAINT foreign_key_name FOREIGN KEY (foreign_key_column)
REFERENCES primary_key_table (primary_key_column) ON DELETE NO ACTION
ON UPDATE CASCADE;
Note if you don't add an index it wont work.
After battling with it for about 6 hours I came up with the solution
I hope this save a soul.
MySQL will execute this query:
ALTER TABLE `db`.`table1`
ADD COLUMN `col_table2_fk` INT UNSIGNED NULL,
ADD INDEX `col_table2_fk_idx` (`col_table2_fk` ASC),
ADD CONSTRAINT `col_table2_fk1`
FOREIGN KEY (`col_table2_fk`)
REFERENCES `db`.`table2` (`table2_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
Cheers!
When you add a foreign key constraint to a table using ALTER TABLE, remember to create the required indexes first.
Create index
Alter table
try all in one query
ALTER TABLE users ADD grade_id SMALLINT UNSIGNED NOT NULL DEFAULT 0,
ADD CONSTRAINT fk_grade_id FOREIGN KEY (grade_id) REFERENCES grades(id);
step 1: run this script
SET FOREIGN_KEY_CHECKS=0;
step 2: add column
ALTER TABLE mileage_unit ADD COLUMN COMPANY_ID BIGINT(20) NOT NULL
step 3: add foreign key to the added column
ALTER TABLE mileage_unit
ADD FOREIGN KEY (COMPANY_ID) REFERENCES company_mst(COMPANY_ID);
step 4: run this script
SET FOREIGN_KEY_CHECKS=1;
ALTER TABLE child_table_name ADD FOREIGN KEY (child_table_column) REFERENCES parent_table_name(parent_table_column);
child_table_name is that table in which we want to add constraint.
child_table_column is that table column in which we want to add foreign key.
parent table is that table from which we want to take reference.
parent_table_column is column name of the parent table from which we take reference
this is basically happens because your tables are in two different charsets. as a example one table created in charset=utf-8 and other tables is created in CHARSET=latin1 so you want be able add foriegn key to these tables. use same charset in both tables then you will be able to add foriegn keys. error 1005 foriegn key constraint incorrectly formed can resolve from this
The foreign key constraint must be the same data type as the primary key in the reference table and column
ALTER TABLE TABLENAME ADD FOREIGN KEY (Column Name) REFERENCES TableName(column name)
Example:-
ALTER TABLE Department ADD FOREIGN KEY (EmployeeId) REFERENCES Employee(EmployeeId)
i geted through the same problem. I my case the table already have data and there were key in this table that was not present in the reference table. So i had to delete this rows that disrespect the constraints and everything worked.
Double check if the engine and charset of the both tables are the same.
If not, it will show this error.

Altering a table primary key which has foreign key constrains in mysql

I have a mysql database which have set of tables One table have a composite key as the primary key and and a single foreign key. Following are the table definitions.
CREATE TABLE IF NOT EXISTS `ohrm_emp_education` (
`emp_number` int(11) NOT NULL,
`education_id` int(11) NOT NULL,
`institute` varchar(100) DEFAULT NULL,
`major` varchar(100) DEFAULT NULL,
`year` decimal(4,0) DEFAULT NULL,
`score` varchar(25) DEFAULT NULL,
`start_date` date DEFAULT NULL,
`end_date` date DEFAULT NULL,
PRIMARY KEY (`emp_number`,`education_id`),
KEY `education_id` (`education_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `ohrm_emp_education`
ADD CONSTRAINT `ohrm_emp_education_ibfk_1` FOREIGN KEY (`emp_number`) REFERENCES `hs_hr_employee` (`emp_number`) ON DELETE CASCADE,
ADD CONSTRAINT `ohrm_emp_education_ibfk_2` FOREIGN KEY (`education_id`) REFERENCES `ohrm_education` (`id`) ON DELETE CASCADE;
But now I need to add a new column to this existing table and make it as the primary key. I tried it with the following query.
ALTER TABLE ohrm_emp_education
ADD column id int not null AUTO_INCREMENT,
DROP PRIMARY KEY,
ADD primary key (id)
But it shows following error
#1025 - Error on rename of './test/#sql-4f6_19b' to './test/ohrm_emp_education' (errno: 150)
I tried with several answers which are found on the internet but couldn't solve it properly. Can someone help me on this. Thanks in advance.
Try to delete foreign keys first, something like this:
ALTER TABLE `ohrm_emp_education` DROP FOREIGN KEY `emp_number`;
ALTER TABLE `ohrm_emp_education` DROP FOREIGN KEY `education_id`;
And then alter table.
If you are using SQL Server Management Studio.
Then right click on the table and click design.
Then right click on the row which contains the composite key
and click on remove primary key
then add new column
and insert data into that column
and check that the column has no empty data.
Then again go to design view
and right click on the required column and click on Set as Primary Key
You're Done!!
You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.
drop/disable foreign key constraint. Drop primary key, add new PK, enable/add fk.