假设一个网站根据发布的媒体格式对热门故事进行分类。其数据库由以下表格组成:
如果一个故事从数据库中删除,它的媒体关联也应该被删除。如果与某种媒体相关的唯一故事被删除,则有关该媒体的信息现在变得无用,也必须删除。
例如,如果蜘蛛侠 (story_id 2) 被删除,它与电影和漫画媒体的链接也应该被删除。由于没有其他故事以漫画的形式发布,因此必须去除以漫画为媒介的信息,而以电影为媒介的任何信息仍然与其他故事相关,必须保持不变。
抽象地说,我想通过以下方式实现这一目标:
//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
或者像这样:
//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)>
作为更好方法的一部分,我将如何实际写出这些查询或其他查询?