Unable to create/drop a foreign key on a MySQL table - mysql

I have searched for the answer to this and only come up with the basic answers on creating/dropping a foreign key etc.
I have a large table and created a foreign key, however during creation the server crashed so the key was not created.
But, if I try to create the key I get a SQL 1005 error "duplicate key on write or update", and if I try to drop the key I get a SQL 1025 error "cannot delete a parent row" which after querying the Innodb engine status translates to "cannot find a constraint with the given id". I cannot find the key by querying the information_schema, so how does MySQL know of its existence when I try to create it and yet cannot find it when I try to drop it, it must be logged somewhere. I am sort of stuck and hoping that I do not have to delete and recreate the table. Any ideas on resolving this welcome.

Related

MySQL "Duplicate Foreign Key", but key doesn't exist

I need to create a foreign key, but executing the following results in the error: "Error Code: 1826. Duplicate foreign key constraint name 'FK_ProjectBase_Program'"
alter table ipos5.ProjectBase
add constraint FK_ProjectBase_Program foreign key (Program) references Program(OID);
If I execute:
select *
from information_schema.TABLE_CONSTRAINTS
where CONSTRAINT_TYPE = 'FOREIGN KEY'
result = def ipos5 FK_ProjectBase_Program ipos5 projectbase FOREIGN KEY
I can see the existing key definition, but if I show the structure for the target TABLE_NAME, it is not there.
This is on an active database with a large amount of data, using InnoDB, so dump/restore is a very last resort.
I am using a 3rd party framework, which does not allow me to manually specify a foreign key name (so I HAVE to use the one specified), but my application errors during startup because it cannot create the key.
Is there a way to rebuild the information_schema database? I am really hoping to avoid doing a dump and rebuild of the application database, as it is quite large.
I ended up duplicating the table structure, copying the data into it, dropping the original table, then re-creating it and copying the data back. Orphaned foreign key reference is now gone.

Magento reindex catalog product flat error: Error in foreign key constraint

I have an error when I try to reindex Magento 1.7 catalog product flat index (through admin panel or command line).
On the command line I get the following error:
Product Flat Data index process unknown error:
exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 1005
Can't create table 'databasename.#sql-340a_22a3' (errno: 121)' in
/var/www/clients/client1/web16/web/lib/Zend/Db/Statement/Pdo.php:228
When I look in mysql using 'SHOW ENGINE INNODB STATUS;', I get the following error:
160830 10:17:09 Error in foreign key constraint creation for table
`databasename`.`#sql-340a_2160`.
A foreign key constraint of name
`databasename`.`FK_MAGE_MAGE_CAT_PRD_FLAT_1_ENTT_ID_MAGE_CAT_PRD_ENTT_ENTT_ID`
already exists. (Note that internally InnoDB adds 'databasename'
in front of the user-defined constraint name.)
Note that InnoDB's FOREIGN KEY system tables store
constraint names as case-insensitive, with the
MySQL standard latin1_swedish_ci collation. If you
create tables or databases whose names differ only in
the character case, then collisions in constraint
names can occur. Workaround: name your constraints
explicitly with unique names.
Any idea how to fix this?
Disable foreign_key_checks MySQL option before reindex
SET foreign_key_checks = 0;
// job
SET foreign_key_checks = 1;
I don't think that disabling foreign key checks is a good idea as it can lead to corrupted lines. In fact, this error is the result of some corrupted lines already.
You may read this thread which is, to me, a better way to resolve this issue: https://magento.stackexchange.com/questions/9974/product-flat-data-wont-reindex/354240

mysql foreign key, wont create mysql error message is Vague

ALTER TABLE cfg_scripts
ADD CONSTRAINT cfg_scripts_priority_fk
FOREIGN KEY (priority)
REFERENCES cfg_script_priorities(script_priority);
Lookup Error - MySQL Database Error: Cannot add foreign key constraint.
mysql fails it tell me actually why it cant
select priority
from cfg_scripts
where coalesce(priority,-1) not in (select script_priority from cfg_script_priorities)
The above query returns no rows, so no key violations.
data types the same, can't see problem
would help if mysql error message could actually tell you the problem... i find mysql's error messaging terrible....

Mysql cannot add or update child row, Foreign key related failure

Error: cannot add or update a child row: foreign key constraint fails
Following is the code that is creating the error:
ALTER TABLE 'catalog_eav_attribute'
ADD CONSTRAINT 'FK_CATALOG_EAV_ATTRIBUTE_ID'
FOREIGN KEY ('attribute_id') REFERENCES 'eav_attribute' ('attribute_id)'
ON DELETE CASCADE ON UPDATE CASCADE;
I uploaded the Structure of SQL and its has no issue , but when i insert the data i am getting the above related error. I read somewhere and i predict its because of lousy data.What are the other possibilities for the error ? Any suggestions or solution will be great.
"For storage engines other than InnoDB, MySQL Server parses the FOREIGN KEY syntax in CREATE TABLE statements, but does not use or store it."
From: http://dev.mysql.com/doc/refman/5.5/en/ansi-diff-foreign-keys.html
I'm not sure, but if your table is MyISAM and not InnoDB, your syntax might not work.
The error message means whatever number you're trying to put into the attribute_id column doesn't yet exist in the eav_attribute.attribute_id column.
Can you insert a value that does already exist in eav_attribute.attribute_id? (You probably can.)
Can you provoke the same error by trying to insert a value that doesn't exist in eav_attribute.attribute_id?
Reconcile the differences, and you're done. You need to determine which attribute ids don't exist in eav_attribute.attribute_id, and fix that.

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

I tried this in mysql:
mysql> alter table region drop column country_id;
And got this:
ERROR 1025 (HY000): Error on rename of './product/#sql-14ae_81' to
'./product/region' (errno: 150)
Any ideas? Foreign key stuff?
You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.
But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:
SHOW CREATE TABLE region;
This should show you the name of the index, something like this:
CONSTRAINT region_ibfk_1 FOREIGN
KEY (country_id) REFERENCES
country (id) ON DELETE NO
ACTION ON UPDATE NO ACTION
Now simply issue an:
alter table region drop foreign key
region_ibfk_1;
And finally an:
alter table region drop column
country_id;
And you are good to go!
It is indeed a foreign key error, you can find out using perror:
shell$ perror 150
MySQL error code 150: Foreign key constraint is incorrectly formed
To find out more details about what failed, you can use SHOW ENGINE INNODB STATUS and look for the LATEST FOREIGN KEY ERROR section it contains details about what is wrong.
In your case, it is most likely cause something is referencing the country_id column.
You can get also get this error trying to drop a non-existing foreign key. So when dropping foreign keys, always make sure they actually exist.
If the foreign key does exist, and you are still getting this error try the following:
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL';
// Drop the foreign key here!
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
This always does the trick for me :)
Simply run the alter table query using 'KEY' instead of 'FOREIGN KEY' in the drop statement. I hope it will help to solve the issue, and will drop the foreign key constraint and you can change the table columns and drop the table.
ALTER TABLE slide_image_sub DROP KEY FK_slide_image_sub;
here in DROP KEY instead of DROP FOREIGN KEY,
hope it will help.
Thanks
I know, this is an old post, but it's the first hit on everyone's favorite search engine if you are looking for error 1025.
However, there is an easy "hack" for fixing this issue:
Before you execute your command(s) you first have to disable the foreign key constraints check using this command:
SET FOREIGN_KEY_CHECKS = 0;
Then you are able to execute your command(s).
After you are done, don't forget to enable the foreign key constraints check again, using this command:
SET FOREIGN_KEY_CHECKS = 1;
Good luck with your endeavor.
I had a similar issues once. I deleted the primary key from TABLE A but when I was trying to delete the foreign key column from table B I was shown the above same error.
You can't drop the foreign key using the column name and to bypass this in PHPMyAdmin or with MySQL, first remove the foreign key constraint before renaming or deleting the attribute.
Take a look in error file for your mysql database. According to Bug #26305 my sql do not give you the cause. This bug exists since MySQL 4.1 ;-)
If you are using a client like MySQL Workbench, right click the desired table from where a foreign key is to be deleted, then select the foreign key tab and delete the indexes.
Then you can run the query like this:
alter table table_name drop foreign_key_col_name;
There is probably another table with a foreign key referencing the primary key you are trying to change.
To find out which table caused the error you can run SHOW ENGINE INNODB STATUS and then look at the LATEST FOREIGN KEY ERROR section
Use SHOW CREATE TABLE categories to show the name of constraint.
Most probably it will be categories_ibfk_1
Use the name to drop the foreign key first and the column then:
ALTER TABLE categories DROP FOREIGN KEY categories_ibfk_1;
ALTER TABLE categories DROP COLUMN assets_id;
I got this error with MySQL 5.6 but it had nothing to do with Foreign keys. This was on a Windows 7 Professional machine acting as a server on a small LAN.
The client application was doing a batch operation that creates a table fills it with some external data then runs a query joining with permanent tables then dropping the "temporary" table. This batch does this approximately 300 times and this particular routine had been running week in week out for several years when suddenly we get the Error 1025 Unable to rename problem at a random point in the batch.
In my case the application was using 4 DDL statements a CREATE TABLE followed by 3 CREATE INDEX, there is no foreign key. However only 2 of the indexes actually get created and the actual table .frm file was renamed, at the point of failure.
My solution was to get rid of the separate CREATE INDEX statements and create them using the CREATE TABLE statement. This at the time of writing has solved the issue for me and my help someone else scratching their head when they find this thread.
I'd guess foreign key constraint problem. Is country_id used as a foreign key in another table?
I'm not DB guru but I think I solved a problem like this (where there was a fk constraint) by removing the fk, doing my alter table stuff and then redoing the fk stuff.
I'll be interested to hear what the outcome is - sometime mysql is pretty cryptic.
In my case, I was using MySQL workbench and I faced the same issue while dropping one of my columns in a table. I could not find the name of the foreign key. I followed the following steps to resolve the issue:
Rt. click on your schema and select 'schema inspector'. This gives you various tables, columns, indexes, ect.
Go to the tab named 'Indexes' and search the name of the column under the column named 'Column'. Once found check the name of the table for this record under the column name 'Table'. If it matches the name of the table you want, then note down the name of the foreign key from the column named 'Name'.
Now execute the query : ALTER table tableNamexx DROP KEY foreignKeyName;
Now you can execute the drop statement which shall execute successfully.
Doing
SET FOREIGN_KEY_CHECKS=0;
before the Operation can also do the trick.
averageRatings= FOREACH groupedRatings GENERATE group AS movieID, AVG(ratings.rating) AS avgRating, COUNT(ratings.rating) AS numRatings;
If you are using any command like above you must use group in small letters. This may solve your problem it solved mine. At least in PIG script.