Created
June 16, 2015 01:30
-
-
Save kissarat/467b284fc53d5dab2427 to your computer and use it in GitHub Desktop.
MySQL. Gets all descendants (children) for given ID of parent with depth parameter
This file contains 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
DROP PROCEDURE IF EXISTS descend; | |
CREATE PROCEDURE descend(uid INT, depth INT) BEGIN | |
DROP TABLE IF EXISTS descendants; | |
DROP TABLE IF EXISTS children; | |
CREATE TEMPORARY TABLE descendants ( | |
id int, | |
parent_id int, | |
level int | |
) ENGINE = MEMORY; | |
INSERT INTO descendants(id, level) | |
VALUES (uid, 0); | |
CREATE TEMPORARY TABLE children LIKE descendants; | |
ALTER TABLE descendants ADD CONSTRAINT UNIQUE(id); | |
iter: LOOP | |
INSERT INTO children | |
SELECT u.id, u.parent_id, level + 1 FROM user u | |
JOIN descendants h ON u.parent_id = h.id | |
WHERE level < depth; | |
DELETE FROM children WHERE id IN (SELECT id FROM descendants); | |
IF (SELECT count(*) FROM children) > 0 THEN | |
INSERT INTO descendants SELECT * FROM children; | |
ELSE | |
LEAVE iter; | |
END IF; | |
END LOOP; | |
SELECT * FROM descendants; | |
# DROP TABLE descendants; | |
# DROP TABLE children; | |
END; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment