I have a table with, let’s say, the following columns:
Name , Parent Name, ID
Let’s also say that there are three entries where Parent Name is Null (meaning they are the top-most parent) – F_one, G_one, and H_one.
If I want to delete all the descendants of one of those parents (G_one, why not?) meaning all the children of G_one, all the children of those children, and the children of those, and so on all the way until the terminal level where, that row’s Name does not exist as a Parent Name for any other entry.
Is that possible to be done easily, maybe with a single query?
Bonus, is there a way to select all of the G_one lineage so I can manipulate it to my whim and will?
Can assume:
-No Children are shared among parents
Cannot assume:
-A discrete or even consistent number of sub-levels.
As @Marc B’s suggestion, a
FORIEGN KEYwithON DELETE CASCADEwould achieve this.If you haven’t one, you can add it now:
If there is a
UNIQUEconstraint onName(I assume thePRIMARYkey osID), skip thi sstep. If there ism’t one, create it:If the previous step succeeded, add the
FOREIGN KEY:If the previous step succeeded, you can now delete your rows with one statement:
This should result in:
Y rows affected.