MySQL嵌套集层次结构与外表

时间:2010-03-31 08:57:32

标签: mysql rdbms nested-sets

我在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`

2 个答案:

答案 0 :(得分:0)

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

  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']}
  3. 这是你需要的。

答案 1 :(得分: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`