问题
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?
回答1:
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;
来源:https://stackoverflow.com/questions/11688067/deleting-from-two-h2-tables-with-a-foreign-key