views:

293

answers:

2

Hi!

I'm using a nested set in a MySQL table to describe a hierarchy of categories, and an additional table describing products.

Category table;

id
name
left
right

Products table;

id
categoryId
name

How can I retrieve the full path, containing all parent categories, of a product? I.e.:

RootCategory > SubCategory 1 > SubCategory 2 > ... > SubCategory n > Product

Say for example that I want to list all products from SubCategory1 and it's sub categories, and with each given Product I want the full tree path to that product - is this possible?

This is as far as I've got - but the structure is not quite right...

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`
A: 

To fetch parents nodes you need only... left/right values of last (SubCategory n) node.

  1. Fetch your product: SELECT ... FROM product p JOIN category c ON c.id = p.category_id WHERE p.id = ?.
  2. Fetch parents: SELECT ... FROM category WHERE leftCol <= {productCategory['left']} AND rightCol >= {productCategory['right']}

That's pretty everthing you need.

Crozin
Thanks, not entirely sure how you mean - I wanted this in one query. Thanks for your input thou - you're welcome to elaborate your answer further!
Björn
A: 

Hey, I think I solved it! :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`
Björn
In the question, you don't mention that the node ids are assigned in an order that allows you to do this. Without this knowledge I don't think it can be done.
reinierpost