2010-03-31 37 views
0

我在MySQL表中使用嵌套集来描述类别的层次结构,以及描述产品的附加表。与外部表的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

嘿,我想我解决了它! :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` 
+0

在这个问题中,您没有提到节点id是按照允许您执行此操作的顺序进行分配的。如果没有这方面的知识,我不认为这是可以做到的。 – reinierpost 2010-04-06 08:00:44

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']}

这就是你需要相当一切。

+0

谢谢,不完全确定你的意思 - 我想在一个查询中。感谢您的意见 - 欢迎您进一步阐述您的答案! – 2010-03-31 09:20:41