I had a table named movies which had the fields id as primary key, and two varchars: title and genre.
I created a new table named genres with the int field id as primary key and desription varchar. I changed the field genre in my movies table so I could create a foreign key referencing a genre.
However, Mysql Workbench says there's an error when creating the foreign key.
Here's the statement:
ALTER TABLE `managemovies`.`movies`
ADD CONSTRAINT `genre_reference`
FOREIGN KEY (`genre` )
REFERENCES `managemovies`.`genres` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION
, ADD INDEX `genre_reference_idx` (`genero` ASC) ;
Error:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (`managemovies`.`#sql-3ba_2b`, CONSTRAINT `genre_reference` FOREIGN KEY (`genre`) REFERENCES `genres` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
SQL Statement: [... same statement than above ... ]
ERROR: Error when running failback script. Details follow.
ERROR 1046: No database selected
SQL Statement:
CREATE TABLE `movies` [...]
[... the errors above repeated again ...]
clear your table contents and try adding foreign key.
if your table contain data which not matching the foreign key field value you will see this error ...
It looks like your table movies has data in genre column which is not present in genres.id column.
Your statement should work after removing the invalid data.
Hope it helps
Vishad
I have faced same issue i got resolved later..
for this answer is simple you just need to add atleast a row of values in both tables then try to add the foreign key
Related
So I've tried to do this a number of ways. Basically I'm given the following instructions:
Using the blog database (use either a single-line or a multi-line SQL statement):
Write a SQL ALTER TABLE statement that adds a post_id column to the blog.comments table.
This new column should be an INTEGER data type with a max. size of 3 digits, UNSIGNED, it should be NOT NULL and it should work as a FOREIGN KEY that uses as a reference the id column of the blog.posts table.
I have no issue adding the column, it's getting the foreign key to work that's stumping me. I used the following code:
ALTER TABLE blog.comments
ADD COLUMN post_id INT(3) UNSIGNED NOT NULL;
ALTER TABLE blog.comments
ADD FOREIGN KEY (post_id) REFERENCES posts(id);
And I keep getting the following error when I submit it:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (b
log.#sql-628_2a, CONSTRAINT #sql-628_2a_ibfk_1 FOREIGN KEY (post_id) REFERENCES
posts (id))
I have tried several different versions but I can't get it to work.
I have a table named "label" with 2 columns:
_LABEL_ID (varchar)
_LENGTH (varchar)
This table already has data in it!
And I have several other Tables "a", "b", "c", etc.
these tables have the column _LABEL_ID (varchar). These table are not empty
On delete of any row from tables a, b, c, ...etc., then delete its label from the "label" table. I tried to add foreign key to "label" referenced to table "a" for doing this (just to test it), but getting the same error like in this question:
can't add foreign key in mysql?
In my case I have InnoDB engine for all tables, unique names FK's, same data types.
Now I exported label rows, then emptied the label table, adding foreign key to it referenced to "a" table works just fine. If i import the rows again to the label table, I get the same error which I got when try to add foreign key.
the rows in label table belong to different tables (a, b, c, ..etc). is this the cause of the error?
i do this using MySQL Workbench
EDIT: the real SQL Statement and the Error Message:
ALTER TABLE `cal_view_db`.`dbo_pub_label`
ADD CONSTRAINT `fk_dbo_pub_label_treenode`
FOREIGN KEY (`_LABEL_ID` )
REFERENCES `cal_view_db`.`dbo_system_treenode` (`_NAME_ID` )
ON DELETE CASCADE
ON UPDATE NO ACTION
, ADD INDEX `fk_dbo_pub_label_treenode_idx` (`_LABEL_ID` ASC) ;
Error Message:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (`cal_view_db`.`#sql-10cc_4a`, CONSTRAINT `fk_dbo_pub_label_treenode` FOREIGN KEY (`_LABEL_ID`) REFERENCES `dbo_system_treenode` (`_NAME_ID`) ON DELETE CASCADE ON UPDATE NO ACTION)
SQL Statement:
ALTER TABLE `cal_view_db`.`dbo_pub_label`
ADD CONSTRAINT `fk_dbo_pub_label_treenode`
FOREIGN KEY (`_LABEL_ID` )
REFERENCES `cal_view_db`.`dbo_system_treenode` (`_NAME_ID` )
ON DELETE CASCADE
ON UPDATE NO ACTION
, ADD INDEX `fk_dbo_pub_label_treenode_idx` (`_LABEL_ID` ASC)
ERROR: Error when running failback script. Details follow.
ERROR 1046: No database selected
SQL Statement:
CREATE TABLE `dbo_pub_label` (
`_LABEL_ID` varchar(45) NOT NULL,
`_LENGTH` varchar(45) DEFAULT NULL,
PRIMARY KEY (`_LABEL_ID`),
KEY `fk_dbo_pub_label_1_idx` (`_LABEL_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
many thanks
p.s: sorry for my bad english!
Yes, it does seem that your problem is that the data in label belongs to multiple tables.
If I am not mistaken then a FK tells the DB to check in the referenced table for every value in the FK Table.
Here, you have labels from a and b and c and d. When the DB goes to verify the FK it will not find the data in label that corresponds to the data in b,c,d,etc. It will only find the ones that are in a.
This is why your error comes up both when you try and create the table and when you try to reload the data to the table. All records in a FK column must have a match in the referenced table. (Here that is label -> FK -> a)
I use MySQL with InnoDB engine. I double-checked type of columns. But always have:
Error Code: 1215. Cannot add foreign key constraint
I tried:
ALTER TABLE `mail`.`boxes`
ADD CONSTRAINT FK_id
FOREIGN KEY (id)
REFERENCES `mail`.`users` (id)
ON UPDATE NO ACTION
ON DELETE NO ACTION;
and
ALTER TABLE `mail`.`boxes`
ADD FOREIGN KEY (id)
REFERENCES `mail`.`users` (id)
Nothing works(((
Please, help, what I am doing wrong (except choosing MySQL :-) )?
If table contains data then you are not able to add foreign key you drop table object and recreate
use below reference for the same
Basics of Foreign Keys in MySQL?
To check what exactly the problem is, use:
SHOW ENGINE INNODB STATUS\G
There is section "last foreign key error". Look at: http://dev.mysql.com/doc/refman/5.0/en/innodb-monitors.html
My guess is that data type od mail.boxes (id) and mail.users (id) is not the same. (E.g. smallint in one table and integer in second one).
Data in table on which you're trying to create FK could possibly also be problem (are your mailbox ids the same as id of existing users?)
I have a table where I keep
id|user_id|subject_id
I have another two table users and subjects.
user_id is a foriegn key and refer the id in users table id column.
I use php admin and I could create the relation.
Same way, I tried to create relation for the subject_id foriegn key.
But I get the following error.
#1452 - Cannot add or update a child row: a foreign key constraint fails (`version2`.<result 2 when explaining filename '#sql-25b4_1e1'>, CONSTRAINT `#sql-25b4_1e1_ibfk_1` FOREIGN KEY (`id`) REFERENCES `wp_cons_table` (`subject_id`))
all tables are ino db and columns have int(5) data type.
I don't know why I get the error.
Can someone figure the reson to this error.
The specific link it's failing on is described at the end of your error:
FOREIGN KEY (`id`) REFERENCES `wp_cons_table` (`subject_id`)
It would be useful to have clearer information about the tables but essentially there are values already in your child table that do not exist in the parent table.
If there is any data that would violate the constraint then you won't be allowed to create it. Delete the mismatched child data or create the parents and you should be fine.
See also: alter table add foreign key fails
MySQL Workbench came up with the following SQL to create a table:
CREATE TABLE IF NOT EXISTS `mydb`.`errors_reports` (
`error_id` INT NOT NULL ,
`report_short` VARCHAR(15) NOT NULL ,
PRIMARY KEY (`error_id`, `report_short`) ,
INDEX `error_id_idx` (`error_id` ASC) ,
INDEX `report_short_idx` (`report_short` ASC) ,
CONSTRAINT `error_id`
FOREIGN KEY (`error_id` )
REFERENCES `mydb`.`errors` (`error_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `report_short`
FOREIGN KEY (`report_short` )
REFERENCES `mydb`.`reports` (`report_short` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
which looks fine to me, and there are a bunch of other very similar tables in my database which MySQL was perfectly happy to create.
But this one...
ERROR 1022 (23000): Can't write; duplicate key in table 'errors_reports'
I can't for the life of me see any duplicate keys here. There's only one key defined!
I'm running MySQL 5.6 with a fresh default install. There's nothing in the error log.
Ideas?
Edit: through a process of elimination (going back to the simplest possible definition of the table, then gradually adding bits back in) the problem appears to be this bit:
CONSTRAINT `error_id`
FOREIGN KEY (`error_id` )
REFERENCES `mydb`.`errors` (`error_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
which is particularly odd as there is identical code in several other table definitions and those are perfectly okay!
The problem is that the name of a foreign key can not be the same as another foreign key in the entire model.
Imagine this situation
Catalog --> Supplier
Product --> Supplier
if the name of the foreign key in table Catalog for supplier is "supplier" and you assigned the same name in product table then the foreign keys names will "collide".
You need to name them differently..
For example:
catalog_supplier
product_supplier
It seems you're creating an index on the foreign key columns. When creating a foreign key in InnoDb, one will be created automatically.
See this thread.
Try using INSERT IGNORE instead of INSERT where INSERT IGNORE will not insert a new row if a duplicate primary key is found. This should help resolve the problem temporary but I would recommend truncating the table.