Last active
March 13, 2019 17:09
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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