我在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`
在這個問題中,您沒有提到節點id是按照允許您執行此操作的順序進行分配的。如果沒有這方面的知識,我不認爲這是可以做到的。 – reinierpost 2010-04-06 08:00:44