This is my table:
CREATE TABLE IF NOT EXISTS `Category` (
`Name` varchar(25) NOT NULL,
`lft` INT UNSIGNED NOT NULL,
`rgt` INT UNSIGNED NOT NULL,
`CategoryId` int UNSIGNED auto_increment NOT NULL,
PRIMARY KEY (`CategoryId`)
) Engine = InnoDb;
I have a url that looks like this: products.php?category=5
From the category id I need to retrieve all the categories with the same parent at each level of the hierarchy. I found a way to do this but I think it is inefficient, is there a better way to do this?
CREATE VIEW category_tree AS
SELECT node.name as name,
node.categoryId as categoryId,
node.lft as lft,
node.rgt as rgt,
(COUNT(parent.categoryId) - 1) AS depth
FROM Category AS node,
Category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY node.categoryId;
SELECT tree.name, tree.depth, tree.categoryId,
(node.lft BETWEEN tree.lft AND tree.rgt) AS is_selected
FROM category_tree as tree
JOIN category_tree AS node ON node.categoryId = :selectedCategory
JOIN (
SELECT MAX(tree.lft) as lft
FROM category_tree as tree
JOIN category_tree AS node ON node.categoryId = :selectedCategory
WHERE
tree.depth = node.depth -1
AND tree.lft < node.lft
) AS parent_finder
LEFT JOIN category_tree AS parent ON parent.lft = parent_finder.lft
WHERE tree.depth < node.depth
OR (
tree.depth = node.depth
AND tree.lft BETWEEN parent.lft AND parent.rgt
)
OR (
tree.lft BETWEEN node.lft AND node.rgt
AND tree.depth <= node.depth + 1
)
ORDER BY tree.depth, tree.name
For example, let's say my category tree looks like this:
(from Managing Hierarchical Data in MySQL)
Let's say the user has selected "cd players", I want to retrieve the following information:
name depth is_selected
electronics 0 1
portable electronics 1 1
televisions 1 0
mp3 players 2 0
cd players 2 1
2 way radios 2 0
I want to retrieve all selected categories and all categories that are at the same level as the selected categories along with depth information and which categories are selected.
The reason I need to do this is so that the products page can include a drop-down navigation menu for every level of category down to the selected category.