0

我在 MySQL 表中使用嵌套集来描述类别层次结构,并使用附加表来描述产品。

类别表;

id
name
left
right

产品表;

id
categoryId
name

如何检索包含所有父类别的产品的完整路径?IE:

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`
4

2 回答 2

0

嘿,我想我解决了!:D

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`
于 2010-03-31T09:19:02.780 回答
0

要获取父节点,您只需要... left/right最后一个(子类别n)节点的值。

  1. 获取您的产品:SELECT ... FROM product p JOIN category c ON c.id = p.category_id WHERE p.id = ?.
  2. 找父母:SELECT ... FROM category WHERE leftCol <= {productCategory['left']} AND rightCol >= {productCategory['right']}

这就是你需要的一切。

于 2010-03-31T09:06:43.413 回答