I have a tag table and three tableA,tableB,tableC tables that are taggable along with three tableA_tag, tableB_tag and tableC_tag tables to join them.
My application allows to remove tags from tableA, tableB or tableC and I want to keep only the tags currently used in one of them.
So far, I’ve wrote the following trigger:
CREATE TRIGGER plop after DELETE
ON tableA_tag
FOR EACH row
DELETE FROM tag
WHERE tag.id = old.tag_id
AND (SELECT Sum(countTags.c) AS s
FROM (SELECT Count(*) AS c
FROM tableC_tag
WHERE tag_id = old.tag_id
UNION
SELECT Count(*) AS c
FROM tableB_tag
WHERE tag_id = old.tag_id) countTags) = 0;
/* Same trigger for table tableB_tag */
/* And same again for table tableC_tag */
But it doesn’t work because it checks if the tag is still used in tableC_tag or tableB_tag but does not check in tableA_tag and can so delete tags even if they are still in use. And I cannot check tableA_tag because it’s the same table that fired the trigger.
So, how can I do ?
Hope this works…