为什么它不在面包屑中显示所有后代类别?
Why isn't it showing all descendant categories in breadcrumbs?
按产品类别搜索时,我需要显示其所有父类别。
当有多个级别时,只显示两个结果。
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 )
结果: T 恤 > 背心
预期结果:男>T恤>背心
不显示“男性”类别
好吧,你只加入了一个级别。如果你想加入任意级别,你可以使用递归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;
按产品类别搜索时,我需要显示其所有父类别。
当有多个级别时,只显示两个结果。
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 )
结果: T 恤 > 背心
预期结果:男>T恤>背心
不显示“男性”类别
好吧,你只加入了一个级别。如果你想加入任意级别,你可以使用递归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;