我在MySQL表中使用嵌套集来描述类别的层次结构,以及描述产品的附加表。
类别表;
id
name
left
right
产品表;
id
categoryId
name
如何检索产品的所有父类别的完整路径?即:
RootCategory > SubCategory 1 > SubCategory 2 > ... > SubCategory n > Product
例如,我想列出SubCategory1
及其子类别中的所有产品,并且每个给定Product
我想要该产品的完整树路径 - 这可能吗?
这是我所拥有的 - 但结构不太合适......
select
parent.`name` as name,
parent.`id` as id,
group_concat(parent.`name` separator '/') as path
from
categories as node,
categories as parent,
(select
inode.`id` as id,
inode.`name` as name
from
categories as inode,
categories as iparent
where
inode.`lft` between iparent.`lft` and iparent.`rgt`
and
iparent.`id`=4 /* The category from which to list products */
order by
inode.`lft`) as sub
where
node.`lft` between parent.`lft` and parent.`rgt`
and
node.`id`=sub.`id`
group by
sub.`id`
order by
node.`lft`
答案 0 :(得分:0)
要获取父节点,您只需要最后一个( SubCategory n )节点的left
/ right
个值。
SELECT ... FROM product p JOIN category c ON c.id = p.category_id WHERE p.id = ?
。SELECT ... FROM category WHERE leftCol <= {productCategory['left']} AND rightCol >= {productCategory['right']}
这是你需要的。
答案 1 :(得分:0)
select
sub.`name` as product,
group_concat(parent.`name` separator ' > ') as name
from
categories as parent,
categories as node,
(select
p.`name` as name,
p.`categoryId` as category
from
categories as node,
categories as parent,
products as p
where
parent.`id`=4 /* The category from which to list products */
and
node.`lft` between parent.`lft` and parent.`rgt`
and
p.`categoryId`=node.`id`) as sub
where
node.`lft` between parent.`lft` and parent.`rgt`
and
node.`id`=sub.`category`
group by
sub.`category`