In MySQL I want to update an ID-column of a table that is referenced in a foreign key constraint within that same table.
Example code:
CREATE TABLE A (
A_id int,
parent_A_id int,
PRIMARY KEY (A_id),
CONSTRAINT parent_A FOREIGN KEY (parent_A_id) REFERENCES A (A_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;
INSERT INTO A VALUES (0, NULL), (1, 0);
Now I try to update the column A_id with
UPDATE A SET A_id = A_id + 1;
Unfortunately this throws an error:
Cannot delete or update a parent row: a foreign key constraint fails
I don't really understand why this fails and I can't find anything in the MySQL docs mentioning this not being allowed.
So, why does this not work?
And in the case that I don't just do a stupid mistake:
Is there any better way of doing such an update other than setting foreign_key_checks = 0 and doing everything by hand?
My problem with this would be that I'd like to use the ON UPDATE CASCADE to let the DB handle all foreign key updates for me.
Related
I've created two tables to do mappings between users. First for users and second for user-mappings. Deletion of users work well, but if I try to update the user id the foreign key constraints from the mapping table fail (without a helpful error output).
CREATE TABLE user (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(55),
PRIMARY KEY (`id`)
);
CREATE TABLE user_map (
map_id INT NOT NULL AUTO_INCREMENT,
user_a INT,
user_b INT,
PRIMARY KEY (`map_id`),
UNIQUE KEY `one_way` (`user_a`,`user_b`),
UNIQUE KEY `other_way` (`user_b`,`user_a`),
CONSTRAINT `acc_connections_ibfk_1` FOREIGN KEY (`user_a`) REFERENCES `user` (`id`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT `acc_connections_ibfk_2` FOREIGN KEY (`user_b`) REFERENCES `user` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
)
Example Data:
INSERT INTO user (name) VALUES ("User A");
INSERT INTO user_map (user_a,user_b) VALUES (1,1);
If I try to update the user id afterwards I get the following error:
Cannot add or update a child row: a foreign key constraint fails
(`test_db`.`user_map`, CONSTRAINT `user_map_ibfk_2`
FOREIGN KEY (`user_b`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
DB Fiddle (Demo)
Interestingly deleting the parent row (user table) succeeds without an error.
What am I doing wrong? I see no reason why this should fail.
I don't know if this is a bug or intended behavior.
As a workaround, if your version of MySql is 8.0.13+, which supports Functional Key Parts, you can use 1 UNIQUE KEY (to check the uniqueness of the combination of the 2 columns) instead of the 2 keys and the UPDATE statement will work:
CREATE TABLE IF NOT EXISTS user_map (
map_id INT NOT NULL AUTO_INCREMENT,
user_a INT,
user_b INT,
PRIMARY KEY (`map_id`),
UNIQUE KEY unk_users((LEAST(`user_a`,`user_b`)), (GREATEST(`user_a`,`user_b`))),
CONSTRAINT `acc_connections_ibfk_1` FOREIGN KEY (`user_a`) REFERENCES `user` (`id`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT `acc_connections_ibfk_2` FOREIGN KEY (`user_b`) REFERENCES `user` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
);
See the demo.
I'm trying to (in a single statement) delete a row and all its relationships, even if all those relationships don't exist. Cascade on delete is not on option, and I would prefer to avoid subqueries.
Here is an example of what fails due to foreign key relationships:
CREATE TABLE test(id integer, title varchar(100), primary key(id));
INSERT into test(id, title) values(1, "Hello");
CREATE TABLE ref_a(id integer, test_id integer, primary key(id), key(test_id), constraint foreign key(test_id) references test(id));
INSERT into ref_a(id, test_id) values(1, 1);
CREATE TABLE ref_b(id integer, test_id integer, primary key(id), key(test_id), constraint foreign key(test_id) references test(id));
SET GLOBAL FOREIGN_KEY_CHECKS=1;
DELETE test, ref_a, ref_b FROM test
LEFT JOIN ref_a ON ref_a.test_id = test.id
LEFT JOIN ref_b ON ref_b.test_id = test.id
WHERE test.id = 1;
This fails with the error
Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (`product`.`ref_a`, CONSTRAINT `ref_a_ibfk_1` FOREIGN KEY (`test_id`) REFERENCES `test` (`id`))
Is this possible to do?
DB is InnoDb. MySql v 5.6.36
For your issue there are three options:
Enable ON DELETE CASCADE.
But that is not an option in your case apparently
Disable foreign_key_checks before running your query, and re-enable it afterwards
Run two queries; first deleting referencing rows (ref_a, ref_b), then the rows in test
Otherwise you this will not be possible, that's what foreign keys are for; to ensure data consistency.
I'm running the following very boring query:
alter table mytable change user_id user_id varchar(36) null default null,
add foreign key (user_id) references users(id) on delete set null;
But it fails with the following error:
#1452 - Cannot add or update a child row: a foreign key constraint fails
(`mydatabase`.`#sql-602_60f`, CONSTRAINT `#sql-602_60f_ibfk_4`
FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL
The problem is that that foreign key constraint doesn't exist, so I can't delete it. There are 3 foreign key constaints on the table (mytable_ibfk_1, mytable_ibfk_2, mytable_ibfk_3), but nothing with the name mentioned, and trying to delete it produces another error.
Any ideas how to fix this?
As Michael Berkowski pointed out, I was misreading the error, which was pointing to conflicting values in the two columns, not to an existing phantom constraint that I couldn't delete.
The root of the problem was that the column had previously accepted empty string values (''), and those needed to be converted to NULL in order for the foreign key constraint to be put in place.
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.
I have set foreign key integrity in a table. But i am able to delete data from the master table, which is reference in child table..
What would be the problem
Actually it should say error on deletion like all referenced table data has to be deleted.
Did you specify ON DELETE CASCADE ? when you created your FK? Don't know which engine you are using either
example
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE
) ENGINE=INNODB;
More here http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
mysql dont do it for you ,
you need declare trigger on delete action
before delete trigger example :
http://www.java2s.com/Code/Oracle/Trigger/Createabeforedeletetrigger.htm