在我的Oracle
数据库中,我希望从2个不同的表中删除行。
问题是,如果我先从KENNEL中删除行,那么我想在DOG表中删除的行不能删除。
以下是要从两个表中删除的SQL statements
。
DELETE FROM KENNEL WHERE COUNTRY_ID IS NULL;
DELETE FROM DOG WHERE ID IN (SELECT DOG_ID FROM KENNEL WHERE COUNTRY_ID IS NULL);
如何解决此问题,以便在同时发生2次删除,并确保删除这两个表中的行?
注意:我无法从DOG中删除KENNEL,因为KENNEL是必须先删除的子记录。
答案 0 :(得分:1)
我会将这组删除视为:
-- delete rows from child table first
DELETE FROM KENNEL WHERE COUNTRY_ID IS NULL;
-- now delete any parent rows that don't have any child records
DELETE FROM DOG WHERE ID not exists (SELECT DOG_ID FROM KENNEL);
这样做意味着如果并非所有kennel表中给定dog_id的country_ids都为null,那么您就不会尝试删除父记录 - 如果您尝试过它会出错。
答案 1 :(得分:0)
UPDATE DOG SET [some non-key field] = 'XXX' WHERE ID IN (SELECT DOG_ID FROM KENNEL WHERE COUNTRY_ID IS NULL);
DELETE FROM KENNEL WHERE COUNTRY_ID IS NULL;
DELETE FROM DOG WHERE [non-key field] = 'XXX';