Creating Relationship in MySQL error - mysql

I have three tables (all InnoDB with primary keys having int(7) for type)
tblcustomers: primary key is customer_id
tblorders: primary key is order_id (has field for customer_id called order_customer)
tblorder_detail: primary key is order_detail_id (has field for order_id called order_id)
I want a to create a relationship so that deleting a customer deletes their order history.
I used the following statement to alter the Orders table:
ALTER TABLE `tblorders`
ADD CONSTRAINT `FK_myKey` FOREIGN KEY (`order_customer`) REFERENCES `tblcustomers` (`customer_id`) ON DELETE CASCADE ON UPDATE CASCADE;
This was successful and deleting a customer deletes their associated orders.
I then tried the following and I get an error:
ALTER TABLE `tblorder_detail`
ADD CONSTRAINT `FK_myKey` FOREIGN KEY (`order_id`) REFERENCES `tblorders` (`order_id`) ON DELETE CASCADE ON UPDATE CASCADE
This is the error (wtc-ecommerce is the name of the db):
1005 - Can't create table 'wtc-ecommerce.#sql-5d2_c2' (errno: 121)
Reading through other SO posts, seems like everything is correctly configured, so I'm lost.
Thanks

Related

SQL - Cannot add or update a child row: a foreign key constraint fails - Pivot table

I'm trying to set up my databse and add some foreign keys but allways getting the following errror :
Cannot add or update a child row: a foreign key constraint fails
I have 3 tables.
groups, categories and categorie_group
the categorie_group table is my pivot table. It only contains a categorie_id and a group_id
Both can be NULL.
groups and cateogires have ID as a primary key
All 3 tables don't have any data yet.
Groups Table:
The ID references the categorie_group - group_id
- on delete cascade on update cascade
Categorie_Group
the group_id of categorie_group references the id of the groups table
on delete no action on update no action
the categorie_id of categorie_group references the id of the categories
table on delete no action on update no action
-------
First problem:
If I want to add a foreign key from the Categories Table ID to the categorie_Group -> categorie_id -
I get a
ALTER TABLE `categories` ADD FOREIGN KEY ( `id` ) REFERENCES `DB`.`categorie_group` (
`categorie_id`
) ON DELETE CASCADE ON UPDATE CASCADE ;
MySQL meldet: Dokumentation
#1452 - Cannot add or update a child row: a foreign key constraint fails (`DB`.`#sql-c40_30a2caf`, CONSTRAINT `#sql-c40_30a2caf_ibfk_1` FOREIGN KEY (`id`) REFERENCES `categorie_group` (`categorie_id`) ON DELETE CASCADE ON UPDATE CASCADE)
seccond Problem, if I want to add data to the groups table I get the same error.
#1452 - Cannot add or update a child row: a foreign key constraint fails (`DB`.`group`, CONSTRAINT `group_ibfk_1` FOREIGN KEY (`id`) REFERENCES `categorie_group` (`group_id`) ON DELETE CASCADE ON UPDATE CASCADE)
You must implement the FK in the child column "categorie_id", not on PK "id". The PK "id" must be referenced and "categorie_id" must do the reference.
Be sure about the column attributes propertyes. Both (primaryKey and FK) must be the same. Or SGBD can't solve the FK:
1- 'Datatype'. The Type (INT, SMALLINT) property as the Size property;
2- 'Accept Null'.
3- 'Unsigned'.
Remember that MyISAM table engine doesn't accept FK constraints, just InnoDB does.
Good Luck.

Two columns in same table and same foreign key

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.

MySQL: Alter table to set Foreign key

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.

Magento - FK_CAT_CTGR_PRD_IDX_PRD_ID_CAT_PRD_ENTT_ENTT_ID foreign key constrait when trying to re-index Category Products

The title says it all really - I'm getting an FK constraint failure when trying to re-index Category Products.
Full exception is:
There was a problem with reindexing process.SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
(`krcscouk`.`catalog_category_product_index`, CONSTRAINT `FK_CAT_CTGR_PRD_IDX_PRD_ID_CAT_PRD_ENTT_ENTT_ID` FOREIGN KEY (`product_id`) REFERENCES `catalog_product_entity` (`entity_id`) ON DELETE)
I've seen it happen on flat tables before, but never on Category Products, and I'm not sure which tables I'll need to look at to get it playing nicely.
The error has your answer:
FK_CAT_CTGR_PRD_IDX_PRD_ID_CAT_PRD_ENTT_ENTT_ID
FK -> Foreign Key
CAT_CTGR_PRD_IDX -> Table Catalog_Category_Product_Index
PRD_ID -> Column Product_ID from the table above
CAT_PRD_ENTT -> Table Catalog_Product_Entity
ENTT_ID -> Column Entity_ID from the table above
So, your problem is that a foreign key from one of these tables to the other fails. Most likely, you have deleted a product and left something in the Catalog_Category_Product_Index. Run the following selects on your database:
SELECT * FROM catalog_category_product_index WHERE product_id NOT IN (SELECT entity_id FROM catalog_product_entity)
Delete those rows from your database and the index process should work.
Go to PhpMyAdmin and run this query:
ALTER TABLE catalog_category_product_index DROP FOREIGN KEY FK_CAT_CTGR_PRD_IDX_PRD_ID_CAT_PRD_ENTT_ENTT_ID
Run Reindexing from Magento Admin Panel or from CLI;
After the reindexing is complete, run this query from PhpMyAdmin:
DELETE FROM catalog_category_product_index WHERE product_id not in (select entity_id from catalog_product_entity); ALTER TABLE catalog_category_product_index ADD CONSTRAINT FK_CAT_CTGR_PRD_IDX_PRD_ID_CAT_PRD_ENTT_ENTT_ID FOREIGN KEY (product_id) REFERENCES catalog_product_entity (entity_id) ON DELETE CASCADE ON UPDATE CASCADE;

Error when inserting multiple MySQL foreign keys

When I try to insert the current table into my table in SQL I get an error (Products table):
CREATE TABLE parent(
Barcode INT(9),
PRIMARY KEY (Barcode)
) ENGINE=INNODB;
CREATE TABLE SuppliedBy(
Onr CHAR(10),
OrgNR INT(10),
Date DATE NOT NULL,
PRIMARY KEY (Onr),
FOREIGN KEY (OrgNR) REFERENCES Supplier(OrgNR)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=INNODB;
CREATE TABLE Products(
Onr CHAR(10),
Barcode INT(9),
Quantity INT(10) DEFAULT 0
CHECK (Quantity >= 0),
PRIMARY KEY (Onr, Barcode),
FOREIGN KEY (Onr) REFERENCES SuppliedBy(SSN)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (Barcode) REFERENCES parent(Barcode)
ON DELETE CASCADE
ON UPDATE CASCADE
)ENGINE=INNODB;
I get the following message:
#1005 - Can't create table '.\db_project\#sql-b58_6d.frm' (errno: 150)
I'm sure it has to do with the several foreign keys in this relation, I searched around on the internet, but can't find the solution.
There is no column SuppliedBy.SSN.
FOREIGN KEY (Onr) REFERENCES SuppliedBy(SSN)
Perhaps you meant
FOREIGN KEY (Onr) REFERENCES SuppliedBy(Onr)
ON DELETE CASCADE
ON UPDATE CASCADE,
I believe the issue is likely that one of the tables you're defining the FOREIGN KEYS to point to does not have an index foreign key field you're pointing to.
For FOREIGN KEY's to work, the field you're pointing to needs to have an index on it.
See Mysql. Can't create table errno 150
Also, check that you meet all the criteria for creating the key. The columns in both tables must:
Be the same datatype
Be the same size or length
Have indexes defined.