I need to write a stored procedure to delete a record from a table.
I have a memory table "tableids" where I store all identifiers for deletion from another table, for example "addresses".
CREATE TABLE `tempids` (
`id` INT(11) NULL DEFAULT NULL
)
COLLATE='latin1_swedish_ci'
ENGINE=MEMORY
ROW_FORMAT=DEFAULT
I could do this:
DELETE FROM addresses INNER JOIN tempids ON addresses.id = tempids.id;
BUT I want to physically delete entries in the address table if they have no links in other known tables of my model; otherwise, I want to logically delete the entries. I would like to do it in one shot, that is, without writing a loop in my SP.
In pseudo-sql code:
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;
How to do it?
Thank.
source
share