2010-03-31 38 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