Can't add foreign key to an existing table - mysql

I want to add foreign key to an existing table questions which has 1000 above questions of different categories in it. But when I am trying to add foreign key mysql throws error as below.
#1452 - Cannot add or update a child row: a foreign key constraint fails (question_bank.#sql-af8_1d0, CONSTRAINTcat_idFOREIGN KEY (cat_id) REFERENCESdb_category(cat_id) ON DELETE NO ACTION ON UPDATE NO ACTION)
category table db_category structure.
questions table db_questions structure.

Before adding a foreign key you should ensure it fits with the actual data.
The error is simple, you have some rows on questions table with wrongs value on cat_id
Just delete that rows, or create new categories. You can check the problematic rows with:
SELECT * FROM questions WHERE cat_id NOT IN (SELECT cat_id from category)

You cant add a foreign key to that table because you must check first if the primary key table has a record exists value same with foreign key table.
according to primary column value and foreign key column value.

Related

PhpMyAdmin error #1452 - Cannot add or update a child row: a foreign key constraint fails

What I want to do is put a Foreign Key from users_table column id into users_order table in the column user_id but when I try to do it says this. what did I do wrong or is there any other way to add foreign key to table in PhpMyAdmin ?
#1452 - Cannot add or update a child row: a foreign key constraint fails (`users`.`#sql-4830_792`, CONSTRAINT `#sql-4830_792_ibfk_1` FOREIGN KEY (`id`) REFERENCES `user_order` (`user_id`))
Users
According to the docs,
For storage engines supporting foreign keys, MySQL rejects any INSERT
or UPDATE operation that attempts to create a foreign key value in a
child table if there is no a matching candidate key value in the
parent table.
The error you see indicates that you are trying to add a new row to a child table, for which mo matching row is present in your parent table. To fix it, you can either add the row in your parent table before inserting a row in your child table, or remove NOT NULL constraints (if any) and insert a NULL value in the corresponding column. Once you do it, you will be able to add the foreign key constraint.
Your error said that
the value that you are inserting into the foreign key does not exists in the parent table.
so before insertion foreign value into child table make sure your value is in parent table
The value should be the same in the primary and index key columns.

child tables and foreign keys

I know there have been myriads of questions concerning primary and foreign keys. Looking through them, I cannot seem to find a simple answer to my question. My understanding of primary and foreign keys is that a foreign key is a column designated in a child table that refers back to a primary key as a column in a parent table. Is that correct, or do I have it backwards? If that is indeed correct, I am trying to find out why I am having difficulty creating a foreign key in a child table as such:
salesorders.sonumber (pk) < customer.sonumber (fk)
I am using Navicat with MariaDB (same as MySQL) and the error I get is:
1452 - Cannot add or update a child row: a foreign key constraint fails ('customer_orders','#sql7a8_3'; CONSTRAINT 'sonumber' FOREIGN KEY ('sonumber') REFERENCES 'salesorder' ('sonumber') ON DELETE NO ACTION ON UPDATE CASCADE)
Customer_orders is the database name. I am naming the foreign key 'sonumber' which is the same as the column name in the child table (customer) and the parent table (salesorders). Is that incorrect? Should I give the foreign key another name?
gitpicker
The foreign key should have its own unique name, yes. sonumber_fk or something similar is a simple naming schema.
You also need to make sure that every entry in the Foreign Key column has a corresponding entry in the Referenced table, otherwise you will not be able to create the foreign key.

Foreign Key Tables Updates

I just started learning SQL so I am a bit confused.
If I have Table A that has a primary key : CustomerID & Table B with foreign key CustomerID
I added the foreign key constraint by using CASCADE so that the foreign key should update or delete automatically when primary key is deleted or updated.
However, it only works for delete. When I add a new record in the primary field table, that record is not shown in the foreign key table, why is that ?
Corresponding rows are updated or deleted in the referencing table
when that row is updated or deleted in the parent table. CASCADE
cannot be specified if a timestamp column is part of either the
foreign key or the referenced key. ON DELETE CASCADE cannot be
specified for a table that has an INSTEAD OF DELETE trigger. ON UPDATE
CASCADE cannot be specified for tables that have INSTEAD OF UPDATE
triggers.
As mention in MSDN. They have mentioned the only update and delete operation of primary key table will affect the Foreign key table's column. If any insert made to primary key, it will not affected the foreign key. Since the Main objective in primary key and foreign key relationship
"An each every record is available in the foreign key table, it should contain corresponding record should be present in the primay key table and vice versa is not applicable".
If you insert any record to foreign key table that it will throws foreign referential integrity error. It will not allows you to insert a record in the foreign table unless and until you will corresponding record in the primary key table.
for information take look in following in MSDN links
http://msdn.microsoft.com/en-us/library/ms179610.aspx
Note:
if you want to achieve this functionality then you have write a logic in Stored procedure or trigger.
No,is not automatic add in your foreign key table , it's not make sense , for example if you have two table ,"City" and "People" , People in the City , so there must be a FK refer for People , if you add record in City e.g. New York , How is database know who's need to insert to People table?How many people? , and what this people properties? e.g. People Name?
So database can't do that automatic , you have to do it manually!

I get Cannot add or update a child row: a foreign key constraint fails error

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

Cannot insert data to table

I am trying to insert data into a table using insert.
INSERT INTO tbl_products (user_id,productkey,listitemname,itemdescription
,thumbnail,rollover,itemfile,themepreview1,themepreview2,themepreview3
,themepreview4,categoryname,sub_category_id,browsercompatiable,filesinclude
,noofcolumns,layout,demourl,itemtags,create_date,update_date,license_number)
VALUES (117,'395cb2e171ac','Baby','This is baby'
,'a4fb673be7b5','d6232cad4955','e3fe02d02c82','dc7067dffd0a','72f48e9a9585'
,'35b016bf135c','6e36d212f3c0','9',51,'ie8,','ie8,',1,1,'http://asdsaf.com'
,'rwreewr','2012-06-30','2012-06-30','1565-5827-7289-918')
But data is not inserted and MySQL shows the following error:
1452 - Cannot add or update a child row: a foreign key constraint
fails (wwwwdmar_orangedoor.tbl_products, CONSTRAINT
tbl_products_ibfk_1 FOREIGN KEY (categoryname) REFERENCES
tbl_sub_categories (sub_category_id) ON DELETE CASCADE ON UPDATE
CASCADE)
Okay, you have a foreign key on tbl_products on the column categoryname. This references the column sub_category_id in tbl_sub_categories.
This stated relationship implies that you must have the value you're inserting for categoryname ('9') in the column sub_category_id of the tbl_sub_categories. It obviously does not exist. Should that 9 really be a string?
Without a lot more information it's technically impossible to help you but here goes:
There are two possibilities:
Hypothesis 1
You have the column categoryname in tbl_sub_categories and the name you're inserting is directly related to the sub_category_id you're also inserting (51).
Solution 1
Remove the column categoryname from tbl_products. There's no need for it to be there in a properly normalised database. Change the foreign key to be a constraint on the column sub_category_id as this is what you seem to be looking up.
Solution 2
Change the foreign key to be on both categoryname and sub_category_id. This is to stop you from inserting values that don't match the referencing columns.
Hypothesis 2
You have a separate table called something like tbl_categories. In this case, you need to reference this table not tbl_sub_categories in your foreign key.