views:

43

answers:

1

Here is my statement :

SELECT (
  COUNT( parent.categoryName ) - ( sub_tree.depth +1 ) ) AS depth,
  CONCAT( REPEAT( '', ( COUNT( parent.categoryName ) - ( sub_tree.depth +1 ) ) ) , node.categoryName ) AS categoryName

FROM 
  Categories AS node,
  Categories AS parent,
  Categories AS sub_parent,
 (
  SELECT node.categoryName, (
     COUNT( parent.categoryName ) -1) AS depth
     FROM 
       Categories AS node,
       Categories AS parent
     WHERE 
       node.categoryLft BETWEEN parent.categoryLft AND parent.categoryRgt
   AND node.categoryName LIKE 'Product'

     GROUP BY node.categoryName
     ORDER BY node.categoryLft
  ) AS sub_tree
WHERE 
    node.categoryLft BETWEEN parent.categoryLft AND parent.categoryRgt
AND node.categoryLft BETWEEN sub_parent.categoryLft AND sub_parent.categoryRgt
AND sub_parent.categoryName = sub_tree.categoryName

GROUP BY node.categoryName
ORDER BY node.categoryLft

It works great, but i would have liked to modify it to get only the first nodes next to the selected category (here 'Products') without the children of the sub categories

Like : Products :

  • TypeA

    • SubTypeA

    • SubTypeB

  • TypeB

I want to get 'TypeA', 'TypeB'.

By the way, here is my table :

CREATE TABLE `Categories` (
 `categoryId` int(11) NOT NULL auto_increment,
 `categoryLft` int(11) NOT NULL,
 `categoryRgt` int(11) NOT NULL,
 `categoryName` varchar(255) default NULL,
 `categoryAlias` varchar(255) default NULL,
 PRIMARY KEY  (`categoryId`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
+1  A: 
SELECT  child.*
FROM    categories parent
JOIN    categories child
ON      child.categoryLft BETWEEN parent.categoryLft AND parent.categoryRgt
WHERE   parent.id = @id_of_products
        AND NOT EXISTS
        (
        SELECT  NULL
        FROM    categories grandchild
        WHERE   grandchild.categoryLft BETWEEN child.categoryLft AND child.categoryRgt
        )

Nested sets model you are using is very hard to manage.

You may want to read this article in my blog:

which describes how to implement a much more simple adjacency list model in MySQL.

Quassnoi