I am working on a forum system and I need to delete all topics and posts from a particular forum.
There is a posts table that holds all the posts. Each post has topic_id field which is the ID of the topic to which it belongs. The topics reside in topics table and each topic has forum_id field which is the ID of the forum it belongs to.
So now when I decide to delete forum with ID 1, how would I go about deleting all topics and posts from this forum as well?
First of all I recommend you take a good look at your data structure: If you use foreign key constraints of the
ON DELETE CASCADEflavour, your sub-deletes will automatically be done for you – and this just one of the advantages you get.If for some reasons you can’t or don’t want to employ such constraints, start by taking a look at how you would select the relvant topics and posts. This should give you quite a good start.
In your particular example something like
and then
should do the trick.
Please understand, that I don’t recommend that. Use data consistency tools for data consistency.