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);
Related
I have a foreign key that references two columns in a child table. Id like to delete the foreign key but mySQL just hangs and nothing happens:
Here is the output from SHOW CREATE TABLE table_name:
KEY FK_animal_index (animal_type,food_index),
CONSTRAINT FK_animal_index FOREIGN KEY (animal_type, food_index)
REFERENCES animal_schedules (animal_type, food_index)
ENGINE=InnoDB
I have tried deleting this foreign key using:
`ALTER TABLE table_name DROP FOREIGN KEY FK_animal_index;`
`ALTER TABLE table_name DROP FOREIGN KEY animal_type;`
ALTER TABLE section_configuration DROP FOREIGN KEY FK_animal_index,
DROP KEY (animal_type, food_index);
AND
ALTER TABLE section_configuration DROP FOREIGN KEYFK_animal_index, ADD CONSTRAINT FK_animal_type FOREIGN KEY (animal_type) REFERENCESanimal_schedules(animal_type) ON DELETE SET NULL;
Others have mentioned that ON DELETE not being set can prevent you changing key values (mySQL will reject the change if ON DELETE is not set to anything)
But to no avail, mySQL just hangs and 30 minutes later still nothing. The database is very small at the moment so removing the FK should be fast.
The answer to this question was not about primary keys at all.
I had to stop my program from accessing the table in order to make modifications to it.
In mySQL db, you can add tables and add columns at any time, but if you want to change a column or remove a column, it must not be in use by any program or it will hang indefinitely.
I have two tables in Mysql named customer_details and transaction table.
I have one column named account_no( primary key in customer_details) and want to relate with account_no field(foreign key in transaction table).
But it is showing error saying Foreign key relation could not be added.
I tried creating index in both columns but still its not working.
ALTER TABLE transaction
ADD INDEX FK_Transaction_AccountNo_idx (AccountNo ASC);
ALTER TABLE transaction
ADD CONSTRAINT FK_Transaction_AccountNo
FOREIGN KEY (AccountNo)
REFERENCES customer_details (AccountNo)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
collation of both table and column should be equal
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 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.
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?)