我必须编写一个存储过程来从表中删除记录。
我有一个内存表“tableid”,在这里我存储了要从另一个表中删除的所有ID,比如“地址”。
CREATE TABLE `tempids` (
`id` INT(11) NULL DEFAULT NULL
)
COLLATE='latin1_swedish_ci'
ENGINE=MEMORY
ROW_FORMAT=DEFAULT
我可以这样做:
DELETE FROM addresses INNER JOIN tempids ON addresses.id = tempids.id;
但是,如果在我的模型中的其他已知表中没有引用,我希望物理上删除地址表中的记录;否则,我希望逻辑上删除这些记录。我想在一次拍摄中做到这一点,即在我的SP中不写循环。
在伪SQL代码中:
DELETE
FROM addresses
WHERE
id NOT IN (SELECT address_id FROM othertable1 WHERE address_id=(SELECT id FROM tempids))
AND id NOT IN (SELECT address_id FROM othertable2 WHERE address_id=(SELECT id FROM tempids))
...more possible references in other tables
IF "no records deleted"
DELETE FROM addresses INNER JOIN tempids ON addresses.id = tempids.id;
ELSE
UPDATE addresses SET deleted=TRUE INNER JOIN tempids ON addresses.id = tempids.id;
我怎样才能做到这一点?
谢谢。