cannot update foreign key in different session mysql - mysql

I have a problem updating a field in a table when i'm in a new session. I have this two tables:
I want to update the idusuario from the pedidos table to reference a different usuario.
I have tried inserting the idusuario fk as null but it neither works
If I execute the update in the same session where I have created the tables there is no problem. See image.
But if I try to execute the same query in another session it crashes with the next error code: (also tried on command line console)

You should drop your foreign key , update , and then re add it :
ALTER TABLE pedidos
DROP FOREIGN KEY FK_name;
UPDATE pedidos set idusuario = 4 where id_pedidos = 2;
ALTER TABLE pedidos
ADD CONSTRAINT FK_name FOREIGN KEY (IdUsuario) REFERENCES SecondTable(idPedidos);

Related

Unable to reuse table name in SQL as constraint still exists

I am trying to rename an empty table with its old name.
I had created constraints in the past (innodb), but that table doesn't exist anymore and if I try to reuse its name (no matter if I create a new table or try to rename another table), I get the following error:
errno: 150 "Foreign key constraint is incorrectly formed"
LATEST FOREIGN KEY ERROR
------------------------
2021-07-16 14:50:24 0x2508 Error in foreign key constraint of table database/publisheremails:
there is no index in the table which would contain
the columns as the first columns, or the data types in the
table do not match the ones in the referenced table
or one of the ON ... SET NULL columns is declared NOT NULL. Constraint:
,
CONSTRAINT `publisheremails_ibfk_1` FOREIGN KEY (`agencyid`) REFERENCES `agencies` (`id`) ON UPDATE CASCADE
I tried to drop the constraint with this code:
ALTER TABLE old_publisheremails
DROP FOREIGN KEY publisheremails_ibfk_1;
I get the following error:
#1091 - Can't DROP FOREIGN KEY publisheremails_ibfk_1; check that it exists
I also tried to drop it with the old table name, but I get this error:
#1146 - Table 'database.publisheremails' doesn't exist
Same goes if I try to drop it from 'agencies'...
Check which foreign keys the table actually has and which name it has with
SELECT
TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
REFERENCED_TABLE_SCHEMA = '<database>' AND
REFERENCED_TABLE_NAME = 'old_publisheremails';
And you can't drop the publisheremails_ibfk_1 because it doesn't exist till now
So check the agencyid column if it has the same data type as agencies (id`) and change it

error with alter table and foreign key

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;

Error while adding Foreign key

I am using Mysql Workbench. I have already made the table.
Now I want to add foreign key in a table called Personal_Details that key is primary key in Login table.
But when I am trying to do so, it shows me the following error:
ERROR 1005: Can't create table 'shaadiDB.#sql-404_25' (errno: 121)
SQL Statement:
ALTER TABLE `shaadiDB`.`Personal_Details`
ADD CONSTRAINT `Login_Id`
FOREIGN KEY (`Login_Id` )
REFERENCES `shaadiDB`.`Login` (`Login_Id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION
, ADD INDEX `Login_Id` (`Login_Id` ASC)
It seems that the table Personal_Details is having data from which there might be some rows with Login_Id for which entry is not present in table Login.
If this is the case , then solution would be that you need to move the data to another table, then add constraint. After adding the constraint you need to add all rows back to table 1 by 1.
Error 121: This error explicitly is thrown when there is a duplication in key names.
Immediately after running your Alter ... statement, execute the following and observe the results.
SHOW ENGINE InnoDB STATUS;
Description text from the result will tell you on which key name the duplication is found.
Based on that you modify your ALTER ... statement and execute.
Alternatively you can also find if any such duplicate key name is defined by executing:
select constraint_name, constraint_type, table_name
from information_schema.table_constraints
where table_schema = DATABASE() -- and constraint_type = 'foreign key'
Constraint types can be anything like PRIMARY KEY, FOREIGN KEY, etc.
If you see any key names in the result that you are trying to use in your ALTER .. statement, you should modify them and execute.
before adding any constrain to a table that already have some data might cause this problem,try to add constrain with out data

MySQL Add foreign key to existing table PHP

I have a built database with all tables set using INNODB and Foreign Keys. Now I need to modify a single table and add a new column which references another table. My query is:
ALTER TABLE test ADD newcol INT NOT NULL;
ALTER TABLE test ADD CONSTRAINT fk_test
FOREIGN KEY (newcol)
REFERENCES othertable(id);
I get the following error:
"#1452 - Cannot add or update a child row: a foreign key constraint fails."
All the other tables contain data, but I know that if I drop the test table and create it with foreign key it will work. If I drop test table it will delete a lot of records and I want to avoid copying data and re-inserting it.
Can anyone show me how to add a new column via a foreign key?
That error message means you have values in newcol that do not exist in othertable id column. By adding a column of INT NOT NULL, you set all the initial values for that column to 0. If you do not have an id of 0 in othertable, you have a key mismatch
Try this query:
SELECT newcol
FROM test
WHERE newcol NOT IN (
SELECT id
FROM othertable
)
if you get any results returned, then you have key values in newcol that violate the FK restraints

MySQL InnoDB - create CASCADE foreign key constraint when data already exists that violates it?

I have a database that was originally in MyISAM and so had no foreign key constraints. As a result, there are quite a few orphaned rows where the record the foreign key refers to has since been deleted.
To fix this I decided to convert to InnoDB and add the foreign keys, with CASCADE for both updating and deleting. However, when I try to add the foreign key, I get errors like this (from Navicat 8 console):
1452 - Cannot add or update a child row: a foreign key constraint fails
(`database`.`#sql-1358_38d`, CONSTRAINT `#sql-1358_38d_ibfk_1` FOREIGN KEY
(`manufacturerID`) REFERENCES `manufacturer` (`ID`) ON DE)
I know why it's doing this - because of the orphaned rows. Is there a way though to have the creation of the constrain automatically clear out those rows? It will take ages to go through all of the tables and find orphaned rows.
This is one of the queries I'm running just in case it is suspect:
ALTER TABLE part_number ADD CONSTRAINT
FOREIGN KEY(manufacturerID)
REFERENCES manufacturer(ID)
ON DELETE CASCADE
ON UPDATE CASCADE;
write a query that finds the orphaned rows and then use that to delete. e.g
SELECT part_number.id FROM part_number LEFT JOIN manufacturer ON (manufacturer.ID = part_number.manufacturerID) where manufacturer.ID IS NULL
You need to get rid of all irrelevant records before you can add a constraint.
You can do it two ways.
1 Using not exists()
DELETE FROM part_number
WHERE NOT EXISTS (
select id from manufacturer
where part_number.manufacturerID = manufacturer.ID
)
2. Using a temporary table (a bit ugly, but i'll post it too)
-- create a temporary table
CREATE TEMPORARY TABLE `temp_ids`
(
`id` INTEGER
);
-- store all id's that need to be deleted
INSERT INTO `temp_ids`
SELECT part_number.id FROM part_number LEFT JOIN manufacturer ON (manufacturer.ID = part_number.manufacturerID)
WHERE ISNULL(`manufacturer.ID);
-- delete them
DELETE
FROM part_number
WHERE id IN (
SELECT `id` FROM `temp_ids`
);
-- drop the table
DROP TEMPORARY TABLE `temp_ids`;
See my related question: Handling database integrity
After all "dead" records are deleted, you will be able to add a constraint.
Hope this works for you :)