Deleting from two h2 tables with a foreign key

我与影子孤独终老i 提交于 2019-12-12 18:54:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!