It is technically possible to perform recursive hierarchical queries in MySQL using stored procedures.
Here is one adapted to your scenario:
CREATE TABLE `user` ( `UserID` int(16) unsigned NOT NULL, `UserName` varchar(32), `ParentID` int(16) DEFAULT NULL, `TopID` int(16) DEFAULT NULL, PRIMARY KEY (`UserID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO user VALUES (1, 'abc', NULL, NULL), (2, 'edf', 1, 1), (3, 'gef', 1, 1), (4, 'huj', 3, 1), (5, 'jdi', 4, 1), (6, 'das', 2, 1), (7, 'new', NULL, NULL), (8, 'gka', 7, 7); DELIMITER $$ DROP PROCEDURE IF EXISTS `Hierarchy` $$ CREATE PROCEDURE `Hierarchy` (IN GivenID INT, IN initial INT) BEGIN DECLARE done INT DEFAULT 0; DECLARE next_id INT;
Time to indicate some reservations :
Since this calls the stored procedure recursively, you need to increase the size of max_sp_recursion_depth , which has a maximum value of 255 (default is 0).
My results on an unoccupied server with limited test data (10 tuples in the user table) took 0.07-0.10 seconds. The performance is such that it is best to place recursion at your application level.
I have not used your TopID column, so there may be a logical flaw. But two tests gave me the expected results.
Disclaimer: This example was just to show that this can be done in MySQL, but not that I approve of it. Stored procedures, temporary tables, and cursors may not be the best way to solve this problem.