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.
Related
Assume I have 2 tables with following attributes.
table 1 (customers): id (PRIMARY), customer (UNIQUE), totalspent
table 2 (receipts): id, cost
What indexes do I need to create on customers or receipts to make it so when a customer is deleted from the table all the receipts tied to him via id are deleted as well?
I set receipts.id to primary key, but when deleting entries from customers, they would not be deleted from receipts. Should I make customers.id a foreign key that references receipts.id? Can a primary key be a foreign key?
You are looking for a cascading foreign key constraint, rather than an index.
alter table receipts add constraint fk_receipts_cust
foreign key (cust) reference customers(id)
on delete cascade;
In MySQL, a foreign key also happens to create an index. This is a "special feature" of MySQL. The functionality you are looking for is the cascading part. You can read more about this in the documentation.
Here is the statement I am executing and related error, any hints what is wrong and how to debug further is appreciated. Using MySQL Workbench/MySQL.
Especially confused what means child row here? How foreign key related to child row? And what is the child row here?
ALTER TABLE Orders
ADD CONSTRAINT fk_Customer FOREIGN KEY (CustomerID)
REFERENCES Customers(CustomerID)
Error Code: 1452. Cannot add or update a child row: a foreign key
constraint fails (test.#sql-ff_2, CONSTRAINT fk_Customer FOREIGN
KEY (CustomerID) REFERENCES Customers (CustomerID))
This error means that your tables contain data that should not be allowed by the foreign key you're trying to create. You could use a query to find them:
SELECT *
FROM orders
WHERE customerid NOT IN (SELECT customerid FROM customers)
If you're sure these rows are indeed faulty, you could use a similar delete statement to remove them:
DELETE FROM orders
WHERE customerid NOT IN (SELECT customerid FROM customers)
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;
Although there are some similar questions about the subject, I can't find the right answer for my problem. I have 2 tables called customer and car. What I want to do is this: When I delete a customer from database, I want the car that belongs to that customer will be automatically deleted as well. The code that MySQL Workbench generated for me is this:
ALTER TABLE `autocare`.`car`
ADD CONSTRAINT `customerId`
FOREIGN KEY (`CUSTOMER_ID`)
REFERENCES `autocare`.`customer` (`ID`)
ON DELETE CASCADE
ON UPDATE RESTRICT;
And I get this error:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails
(`autocare`.`#sql-80c_388`, CONSTRAINT `customerId` FOREIGN KEY (`CUSTOMER_ID`)
REFERENCES `customer` (`ID`) ON DELETE CASCADE)
There was no relation between those tables before. Any ideas? Thanks in advance!
Your goal is ultimately to implement a cascading deletion from customer to car. When you attempt to add the constraint with the tables as they are now, it fails because the car table must include rows having a a CUSTOMER_ID value which does not currently exist in the parent customer table.
You should first locate those orphan rows and delete them (since your goal is to delete them anyway). You can find them with a query like:
SELECT *
FROM car
WHERE
CUSTOMER_ID NOT IN (SELECT ID FROM customer)
Once the orphan records are removed, the foreign key constraint can be met by the remaining existing rows and your ALTER TABLE statement will succeed.
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