Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hollodotme/1beaa402fdfb14c06b62 to your computer and use it in GitHub Desktop.
Save hollodotme/1beaa402fdfb14c06b62 to your computer and use it in GitHub Desktop.

How to read a path of an arbitrary leaf up to the root of the tree in a MySQL parent-child table with one single query

SELECT categories.name, categories.id, categories.parent_id, categories.depth
FROM (
    SELECT
                @id AS _id,
                (
                    SELECT @id := parent_id
                    FROM categories
                    WHERE id = _id
                )
        FROM (SELECT @id := 43) AS tmp1
        JOIN categories ON @id IS NOT NULL
    ) tmp2
JOIN categories ON tmp2._id = categories.id
ORDER BY categories.depth ASC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment