Skip to content

Instantly share code, notes, and snippets.

@devzorg
Created March 21, 2020 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devzorg/6d7a253f1b4f9e2025629c02fa830200 to your computer and use it in GitHub Desktop.
Save devzorg/6d7a253f1b4f9e2025629c02fa830200 to your computer and use it in GitHub Desktop.
-- full path by child id
WITH RECURSIVE category_path (id, title, parent_id) AS
(
SELECT id, title, parent_id
FROM magedev_seotree
WHERE id = 17 AND store_id=1
UNION ALL
SELECT c.id, c.title, c.parent_id
FROM category_path AS cp JOIN magedev_seotree AS c
ON cp.parent_id = c.id
)
SELECT * FROM category_path;
-- sub tree by id
WITH RECURSIVE category_path (id, title, path) AS
(
SELECT id, title, title as path
FROM magedev_seotree
WHERE parent_id = 0 AND store_id=1
UNION ALL
SELECT c.id, c.title, CONCAT(cp.path, ' > ', c.title)
FROM category_path AS cp JOIN magedev_seotree AS c
ON cp.id = c.parent_id
)
SELECT * FROM category_path ORDER BY path;
-- whole tree
WITH RECURSIVE category_path (id, title, path) AS
(
SELECT id, title, title as path
FROM magedev_seotree
WHERE parent_id IS NULL
UNION ALL
SELECT c.id, c.title, CONCAT(cp.path, ' > ', c.title)
FROM category_path AS cp JOIN magedev_seotree AS c
ON cp.id = c.parent_id
)
SELECT * FROM category_path ORDER BY path;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment