Skip to content

Instantly share code, notes, and snippets.

@kissarat
Created June 16, 2015 01:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kissarat/467b284fc53d5dab2427 to your computer and use it in GitHub Desktop.
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
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