How to find all child rows in MySQL?

后端 未结 3 2041
再見小時候
再見小時候 2021-01-27 09:29

I have a hierarchy system setup that stores the level and parent ID of the item in a database. What I am trying to figure out is how would I go about finding all the child rows

3条回答
  •  遇见更好的自我
    2021-01-27 10:14

    Assuming you are on MySQL 5 that has triggers you can write a small before delete trigger to achieve this easily. I have not checked the syntax exactly but will match more or less with the following:

    CREATE TRIGGER tr_tablename_bd BEFORE DELETE ON tablename
      FOR EACH ROW BEGIN
        DELETE FROM tablename WHERE parentID = deleted.id
    END;
    

    The above code will also work with unlimited levels and not just 3 levels. You will need to delete a row and the trigger will delete the rows of data in the below levels or rows that mark the deleted row as parentID.

    I however, vaguely remember an issue with MySQL wherein it failed to launch cascaded triggers. Meaning MySQL fails to fire a trigger due to an action on another trigger. If that bug is still there in the release of MySQL you are using (or even the latest edition) then this code will not work. However, in theory it is perfectly ok and will work on every other database that has triggers for sure. For MySQL you just need to check up if they have managed to resolve that bug yet!

提交回复
热议问题