MY SQL Foreign Key Constraint Error - mysql

I m using MySQL database as back end for my application. I was playing with database and i did something wrong couple of days ago and now i am not able to apply foreign key on my DB Table.
I have 2 tables shoplocation and pizaorderdetail. In pizzaordrdetail i am passing id from shoplocation as foreign key. And i am getting following error. The table already contains data in it. And earlier i had foreign key constraint available on pizzaorderdetail but somehow it got deleted. Please help me out how to resolve this error.
Executing:
ALTER TABLE order.pizzaorderdetail
ADD INDEX FK_idx (LocationID ASC);
ALTER TABLE order.pizzaorderdetail
ADD CONSTRAINT FK
FOREIGN KEY (LocationID)
REFERENCES order.location (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
Operation failed: There was an error while applying the SQL script to the database.
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (order.#sql-714_31, CONSTRAINT FK FOREIGN KEY (LocationID) REFERENCES location (id) ON DELETE NO ACTION ON UPDATE NO ACTION)
SQL Statement:
ALTER TABLE order.pizzaorderdetail
ADD CONSTRAINT FK
FOREIGN KEY (LocationID)
REFERENCES order.location (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION

You need to check if your FK is ok. When I recieved this message, I just deleted my FK's and it was solved.
According to manual: https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
InnoDB reports this error when you attempt to drop the last index that
can enforce a particular referential constraint.
For optimal performance with DML statements, InnoDB requires an index
to exist on foreign key columns, so that UPDATE and DELETE operations
on a parent table can easily check whether corresponding rows exist in
the child table. MySQL creates or drops such indexes automatically
when needed, as a side-effect of CREATE TABLE, CREATE INDEX, and ALTER
TABLE statements.
When you drop an index, InnoDB checks if the index is used for
checking a foreign key constraint. It is still OK to drop the index if
there is another index that can be used to enforce the same
constraint. InnoDB prevents you from dropping the last index that can
enforce a particular referential constraint.

Related

Delete all data from MySQL table which has a foreign key constraint to itself with DBUnit

I am using DBUnit with a MySQL database. The DBUnit default CLEAN_INSERT issues a "DELETE FROM" statement without WHERE clause for the tables with test data. With MySQL this fails for a table which has a foreign key constraint to itself with the following error message:
Cannot delete or update a parent row: a foreign key constraint fails
How should I configure DBUnit to clean the test data correctly in this case?
One possibility is to disable foreign key checks for the session. However I am not sure where the best place to do this is in DBUnit. I would not want to disable the checks for the code under test itself, but at most for the setup/teardown of the test data.
Deleting from a MySQL table with foreign key constraints asks a similar question, but there the foreign key constraint references a different table. The solution of adding ON DELETE CASCADE to the foreign key definition works but I don't want to alter the table definition for my test.
Background Information
Apparently this is a missing feature in MySQL. Quoting from InnoDB and FOREIGN KEY Constraints:
Like MySQL in general, in an SQL statement that inserts, deletes, or updates many rows, InnoDB checks UNIQUE and FOREIGN KEY constraints row-by-row. ... InnoDB checks foreign key constraints immediately; the check is not deferred to transaction commit. According to the SQL standard, the default behavior should be deferred checking. That is, constraints are only checked after the entire SQL statement has been processed. Until InnoDB implements deferred constraint checking, some things will be impossible, such as deleting a record that refers to itself using a foreign key.
Here is a SQL script which reproduces the error:
create table foo (
foo_id varchar(255) NOT NULL,
other_foo_id varchar(255),
PRIMARY KEY (foo_id),
CONSTRAINT FK_other_foo_id FOREIGN KEY (other_foo_id) REFERENCES foo (foo_id)
);
insert into foo values ('foo-id-1',null);
insert into foo values ('foo-id-2','foo-id-1');
delete from foo;
The delete statement fails with error
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (coverage_integration_test.foo, CONSTRAINT FK_other_foo_id FOREIGN KEY (other_foo_id) REFERENCES foo (foo_id))
Tested with MySQL 5.5.40.

MySQL: FK constraint checked between empty tables when truncating

I was truncating tables like this
TRUNCATE TABLE `enterprise_url_rewrite`; -- error
TRUNCATE TABLE `enterprise_catalog_category_rewrite`; -- works fine
in that order or reversed when I got this error.
Cannot truncate a table referenced in a foreign key constraint
(`magento`.`enterprise_catalog_category_rewrite`, CONSTRAINT
`FK_415B32DA3DF924D5C803CF24EB3AC1D9` FOREIGN KEY (`url_rewrite_id`) REFERENCES
`magento`.`enterprise_url_rewrite` (`url_rewrite_id`)
I thought foreign key constraints were enforced to prevent deletion when there are actual values being referenced. I recollect (I could be wrong) being able to TRUNCATE this table previously without disabling key checks. Note that DELETE FROM enterprise_url_rewrite works.
More info on the constraint definition on enterprise_catalog_category_rewrite.
KEY `FK_744D72D1D79D148B7C2542E53B0370B5` (`url_rewrite_id`),
CONSTRAINT `FK_744D72D1D79D148B7C2542E53B0370B5` FOREIGN KEY (`url_rewrite_id`)
REFERENCES `enterprise_url_rewrite` (`url_rewrite_id`) ON DELETE CASCADE ON UPDATE NO ACTION

How to add foreign key to MySQL table?

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?)

How do I delete a foreign key that does not exist from a table that does not exist, in MySQL?

I'm trying to rename a primary key in an InnoDB table and I kept getting an Errno 150. SHOW INNODB STATUS shows:
LATEST FOREIGN KEY ERROR
130711 18:22:53 Error in foreign key constraint of table xx/client_location_business_load:
there is no index in referenced table which would contain
the columns as the first columns, or the data types in the
referenced table do not match the ones in table. Constraint:
,
CONSTRAINT "business_load_business_load_name_key" FOREIGN KEY ("name_id") REFERENCES "client_businesstype_load_name" ("name_id") ON DELETE CASCADE ON UPDATE CASCADE
The table client_location_business_load does not even exist! It was renamed. The constraint named business_load_business_load_name_key does not exist either, it was dropped and it does not appear in information_schema.key_column_usage.
Does anyone have a clue about what's going on here?
You have to drop the database and recreate it in the same collation. There does not seem to be an alternative.

Mysql error code 1452 with two tables with different database engines

I have two tables 'mm_ads' and 'mm_users'. 'mm_ads' uses the Myisam database engine, while 'mm_users' uses a InnoDb. From what I read it is impossible to create a foreign key reference in such a situation, becaues the latter engine is transactional and the first one is not. But when I run:
ALTER TABLE mm_ads ADD CONSTRAINT FK_76EC3E1DF132696E3358 FOREIGN KEY (userid) REFERENCES mm_users (id)
No error is shown, it reports the number of effected rows and nothing else. Than I see that the fk is not created just an index on the column in the table. As I studied the problem I found out that the engines of tables are different so I changed the engine of mm_ads to Innodb. But then when I run the command I get this error.
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`admin_pw`.<result 2 when explaining filename '#sql-61b_3019e'>, CONSTRAINT `FK_76EC3E1DF132696E3358` FOREIGN KEY (`userid`) REFERENCES `mm_users` (`id`))
The types of userid and id are the same and I have values in the tables.
I would do the following:
1. Drop The Foreign Key
ALTER TABLE mm_ads DROP FOREIGN KEY `FK_76EC3E1DF132696E3358`;
2. Indentify Orphaned Rows In Child Table
SELECT * FROM mm_ads when userid not in (select id from mm_users);
3. Deal With Orphaned Rows In Child Table
Delete rows from mm_ads? Insert rows into mm_users? Up to you here. Either way you must end up with no orphaned rows in mm_ads based on the mm_ads.userid > mm_users.id relationship.
4. Change Engine
ALTER TABLE mm_ads ENGINE = InnoDB;
5. Restore Foreign Key
ALTER TABLE mm_ads ADD CONSTRAINT FK_76EC3E1DF132696E3358 FOREIGN KEY (userid) REFERENCES mm_users (id);