0

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`
4

2 に答える 2

0

親ノードをフェッチするには、必要なのは... left/right最後の(SubCategory 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']}

それはあなたが必要とするかなりすべてです。

于 2010-03-31T09:06:43.413 に答える
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`
于 2010-03-31T09:19:02.780 に答える