I have a MySQL table like this:
| CategoryId | Name | CategoryParentId |
|------------|---------------|------------------|
| 0 | Tech Support | (null) |
| 1 | Configuration | 0 |
| 2 | Questions | 1 |
| 3 | Sales | (null) |
| 4 | Questions | 3 |
| 5 | Other | (null) |
This is the output I desire when a query the ID 2 (for example):
Tech Support/Configuration/Questions
How do I do this without having to do multiple joins?
EDIT: Not sure if is the best way to do this, but I solved by creating a function:
DELIMITER $$
CREATE FUNCTION get_full_tree (CategoryId int) RETURNS VARCHAR(200)
BEGIN
SET @CategoryParentId = (SELECT CategoryParentId FROM category c WHERE c.CategoryId = CategoryId);
SET @Tree = (SELECT Name FROM category c WHERE c.CategoryId = CategoryId);
WHILE (@CategoryParentId IS NOT NULL) DO
SET @ParentName = (SELECT Name FROM category c WHERE c.CategoryId = @CategoryParentId);
SET @Tree = CONCAT(@ParentName, '/', @Tree);
SET @CategoryParentId = (SELECT CategoryParentId FROM category c WHERE c.CategoryId = @CategoryParentId);
END WHILE;
RETURN @Tree;
END $$
DELIMITER ;
I can now do this query:
SELECT CategoryId, get_full_tree(CategoryId) FROM category