Suppose a site categorizes popular stories according to the media format in which they are released. Its database consists of the following tables:
If a story is deleted from the database, its media associations should also be removed. If the only story associated with a certain type of media gets deleted, the information about that medium has now become useless and must also be deleted.
For example, if Spiderman (story_id 2) is deleted, its links to movie and comic media should also be removed. Because no other stories are released in the form of a comic, the information about comics as a medium must be removed, while any information on movies as a medium is still relevant for other stories and must remain untouched.
Abstractly, I thought of achieving this in the following way:
//delete the story itself:
DELETE FROM stories WHERE stories.story_id = 2
//delete its links to media:
DELETE FROM links WHERE links.story_id = 2
//delete any media that might subsequently no longer have any links to them:
DELETE FROM media WHERE media.medium_id does not occur in links.medium_id
Or like this:
//delete the story itself:
DELETE FROM stories WHERE stories.story_id = 2
//fetch its associated media ids:
SELECT links.medium_id FROM links WHERE links.story_id = 2
//delete the story's links to any media:
DELETE FROM links WHERE links.story_id = 2
//consider deleting the types of media of which a story has just been deleted:
DELETE FROM media WHERE media.medium_id does not occur in links.medium_id and medium.medium_id = <previously fetched medium id(s)>
How would I actually write out these queries, or other queries, as part of, perhaps, a better approach?