When searching by product category, I need to display all of its parent categories.
When there are multiple levels, it only displays two results.
CREATE TABLE `category` (
`id` int NOT NULL,
`parent_category_id` int,
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB;
INSERT INTO `category` (`id`, `parent_category_id`, `name`) VALUES
(1, NULL, 'Male'),
(2, 1, 'T-shirts'),
(3, 1, 'Shoes'),
(4, 2, 'Tank top'),
(5, 2, 'Basic shirts');
SELECT CONCAT(t1.name, ' > ', t2.name) as breadcrumb
FROM category AS t1
LEFT JOIN category AS t2 ON t2.parent_category_id = t1.id
WHERE t2.id = 4; #( 4 or 5 )
Result: T-shirts > Tank top
Expected outcome: Male > T-shirts > Tank top
Does not display the "Male" category
CodePudding user response:
Well, you only join one level. If you want to join arbitrary levels, you can use a recursive CTE.
WITH RECURSIVE
breadcrumbs
AS
(
SELECT 1 AS ordinality,
c.name,
c.subcategory_id
FROM category AS c
WHERE c.id = 4
UNION ALL
SELECT bc.ordinality 1 AS ordinality,
c.name,
c.subcategory_id
FROM breadcrumbs AS bc
INNER JOIN category AS c
ON c.id = bc.subcategory_id
)
SELECT group_concat(bc.name
ORDER BY bc.ordinality DESC
SEPARATOR ' > ') AS breadcrumb
FROM breadcrumbs AS bc;