Optimize delete_hierarchy_references for MySQL

For my setup when hierarchy table have over million rows, the original query takes over 5 sec making the rebuild! operation impossible; Proposed query takes less than 1ms on MySQL.
I'm not sure how to make the code aware of the DB engine and use the right query, feel free to patch a better solution.