Skip to content

Instantly share code, notes, and snippets.

@strategy
Last active April 6, 2017 13:53
Show Gist options
  • Save strategy/35ff78d8295cf416ec0e9d77b8994c7d to your computer and use it in GitHub Desktop.
Save strategy/35ff78d8295cf416ec0e9d77b8994c7d to your computer and use it in GitHub Desktop.
MySQL recursive tree find
-- Variables to change
-- L13: menu (mysql table)
-- L14: id_menu (mysql table id)
-- L18: 304 (child id from where to start finding the root id)
-- @ref: https://explainextended.com/2009/07/20/hierarchical-data-in-mysql-parents-and-children-in-one-query/
SELECT CONCAT(REPEAT(' ', level - 1), CAST(_id AS CHAR)) AS treeitem,
parent,
level
FROM (
SELECT @r AS _id,
(
SELECT @r := parent_menu_id
FROM menu
WHERE id_menu = _id
) AS parent,
@l := @l + 1 AS level
FROM (
SELECT @r := 304,
@l := 0
) vars,
menu h
WHERE @r <> 0
) q
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment