Skip to content

Instantly share code, notes, and snippets.

@Maykonn
Last active March 13, 2019 17:09
Show Gist options
  • Save Maykonn/c139a6e03094da0c7f975ee5df81f078 to your computer and use it in GitHub Desktop.
Save Maykonn/c139a6e03094da0c7f975ee5df81f078 to your computer and use it in GitHub Desktop.
[SQL] Retrieves results in a hierarchy starting from a specific register (recursive parent_id)
/**
* Retrieves a customer group hierarchy.
* Change the @root_id value to change the hierarchy root.
*/
SET @root_id = 1;
SELECT *
FROM (
SELECT * FROM tbl
ORDER BY parent_id, id) hiearchy_sorted,
(SELECT @pv := @root_id) root_id
WHERE
find_in_set(parent_id, @pv)
AND length(@pv := concat(@pv, ',', id));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment