Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting from two h2 tables with a foreign key

I have an h2 database with two tables with foreign keys like

CREATE TABLE master (masterId INT PRIMARY KEY, slaveId INT);
CREATE TABLE slave (slaveId INT PRIMARY KEY, something INT,
    CONSTRAINT fk FOREIGN KEY (slaveId) REFERENCES master(slaveId));

and need something like

DELETE master, slave FROM master m JOIN slave s ON m.slaveId = s.slaveId
    WHERE something = 43;

i.e., delete from both tables (which AFAIK works in MySql). Because of the FOREIGN KEY I can't delete from the master first. When I start by deleting from the slave, I lose the information which rows to delete from the master. Using ON DELETE CASCADE would help, but I don't want it happen automatically every time. Should I allow it temporarily? Should I use a temporary table or what is the best solution?

like image 418
maaartinus Avatar asked Jan 15 '23 23:01

maaartinus


1 Answers

Nobody answers, but it's actually trivial:

SET REFERENTIAL_INTEGRITY FALSE;
BEGIN TRANSACTION;
DELETE FROM master WHERE slaveId IN (SELECT slaveId FROM slave WHERE something = 43);
DELETE FROM slave WHERE something = 43;
COMMIT;
SET REFERENTIAL_INTEGRITY TRUE;
like image 114
maaartinus Avatar answered Jan 30 '23 22:01

maaartinus