The query works by iterating over the t_list table (last row). For each row in this table, a subquery in the SELECT re-queries the table, looking for the current child of the row ( WHERE parent = _parent - but _parent is an alias for @r ). At each iteration, the child id assigned to the @r variable.
To add boundaries, this option should do the trick:
SELECT * FROM ( SELECT @r AS _parent, @r := ( SELECT id FROM t_list WHERE ( @c = 0 AND _parent IS NULL AND parent IS NULL )
Replace @start and @limit with the id first element and the maximum number of elements to extract, respectively. Please test it here .
Modeling such a data structure using a DBMS is probably a bad idea. Why not just use the index column? Listing becomes instant:
SELECT * FROM list ORDER BY index_column ASC;
Perhaps your list is intended to change often, but such queries should be fast enough if the list is not very large:
-- insert an element at position X UPDATE list SET index_column = index_column +1 WHERE index_column > X ORDER BY index_column DESC; INSERT INTO list VALUE (some_value, X); -- delete an element at position X DELETE FROM list WHERE index_column = X; UPDATE list SET index_column = index_column -1 WHERE index_column > X ORDER BY index_column ASC;
source share