I cannot add a foreign key to my exists table. I want to add a foreign key publisher_id from table games references to publishers (publisher_id).
But when running the below sql, it says:
Source and target columns must have the same data type, there must be an index on the target columns and referenced data must exist.
Cannot add or update a child row: a foreign key constraint fails (vngarena.com.#sql-818_1b1, CONSTRAINT #sql-818_1b1_ibfk_2 FOREIGN KEY (publisher_id) REFERENCES publishers (publisher_id) ON DELETE CASCADE ON UPDATE CASCADE
The sql is:
ALTER TABLE games
ADD FOREIGN KEY (publisher_id) REFERENCES publishers (publisher_id) ON DELETE CASCADE ON UPDATE CASCADE;
And here is the diagram of my db:
More info:
- Table games has two records
- Table games has other foreign key which references to table gamecats (gamecat_id)
- Table gamecats has two records
- Table publishers has no record
If there is any existing data that violates the relationship, you will need to clean it up before adding the key.
[Edited]
After your edit: The publisher_id in Table games, is looking for a match in the publishers table. Add a publisher with an id that matches what's in the games table.
You need to delete the games table records before adding foreign key.
If you add foreign key,it should match with existing data. In your condition the publishers table has no records . so it will fails foreign key if you add data with records in games table
or
You should add two records in publishers table with same keys exists in games table.
For more detail, refer below link
Foreign Key
Related
I am trying to set a FK and I am getting an error
My datatypes are same as reference table.My Artists table contain all the names and I created another table for artist images.
Tables:
ALTER TABLE Artist_Images
ADD CONSTRAINT FK_Artist_Images_Artist
FOREIGN KEY (Artist)
REFERENCES Artists (Artist)
#1215 - Cannot add foreign key constraint
Is it because Artist isnt a PK in Artists table and can't be used as PK? Any other suggestions on how can I link the tables?
One of the most common reason for not being able to create a foreign key when data exists is that the column in the table you are trying to add the key to has values which do not exist in the referenced table.
In this case, you can check for that by running the following query:
SELECT i.Image, i.Artist FROM Artist_Images i
LEFT JOIN Artists a on i.Artist = a.Artist
WHERE a.Artist IS NULL
If you get any rows, you need to resolve that before you can create the foreign key.
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.
I'm developing an application, actually a billing system. Here accountant can add invoice for a client.
I have two tables, users and invoices:
invoices (user_id, created_by)
users (id)
Invoices has two columns, user_id and created_by, I want both to be linked with id of the users table.
Already user_id has been added as foreign key. Now I'm trying to add created_by as foreign key. So issued following command:
ALTER TABLE `invoices`
ADD FOREIGN KEY (`created_by`) REFERENCES `secureap_maind`.`users` (`id`)
ON DELETE RESTRICT ON UPDATE RESTRICT;
And I'm getting an error message.
#1452 - Cannot add or update a child row: a foreign key constraint fails (secureap_maind.#sql-3717_a323d, CONSTRAINT #sql-3717_a323d_ibfk_2 FOREIGN KEY (created_by) REFERENCES users (id))
I'm not sure if I can add two columns as foreign key. IF possible, can you please advice to do that?
Thanks in advance.
This SO post implies that removing your ON DELETE RESTRICT clause from the ALTER TABLE statement might solve your problem. Try running this query instead:
ALTER TABLE `invoices`
ADD FOREIGN KEY (`created_by`) REFERENCES `secureap_maind`.`users`(`id`)
I am assuming that the invoices table was created using InnoDB rather than MyISAM, the latter which does not enforce foreign keys.
I have 2 tables :
Installers (Fields: id,company,country,experience,name)
Contacts (Fields: name,phone,address)
I would like to match both names, thereby I could click in one value of the name of Installers and it could show me the values of Contacts table.
However when I am trying to set up the foreign key (my child table will probably be Installers , as I have more tables like that and Contacts would be the parent.) It states this error:
query SQL:
ALTER TABLE `Installers`
ADD FOREIGN KEY (`name`)
REFERENCES `SOLAR_PV`.`Contacts`(`name`)
ON DELETE CASCADE ON UPDATE CASCADE;
MySQL ha dicho: Documentación
1452 - Cannot add or update a child row: a foreign key constraint
fails (SOLAR_PV.#sql-32a_183, CONSTRAINT #sql-32a_183_ibfk_1
FOREIGN KEY (name) REFERENCES Contacts (name) ON DELETE CASCADE
ON UPDATE CASCADE)
Both tables are InnoDB and Contacts.name is indexed as well as Installers.name
Primary Key of Installers is id and Primary Key of Contacs is name.
Any idea about what would be the problem?
It seems your child table contains few records those don't have in master, you can check it by below query-
SELECT id FROM Installers ins
LEFT JOIN SOLAR_PV.Contacts cnt ON ins.name=cnt.name
WHERE cnt.name IS NULL;
Note: Assuming name is int type for better performance as it is primary key in one table.
If you get few records by above query then you can follow below 2 approach-
Approach1: You can either delete these records in child table or insert in master table also and then you can create relationship by this alter command.
Approach2: If you don't want to change in your tables existing data and still want to execute your alter query then use as per below-
SET FOREIGN_KEY_CHECKS=0;
ALTER TABLE `Installers`
ADD FOREIGN KEY (`name`)
REFERENCES `SOLAR_PV`.`Contacts`(`name`)
ON DELETE CASCADE ON UPDATE CASCADE;
SET FOREIGN_KEY_CHECKS=1;
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!