以下是我的发言:
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
它运行良好,但我本来希望修改它以只获得所选类别旁边的第一个节点(此处为'Products')而没有子类别的子项
喜欢: 产品:
类型A
SubTypeA
SubTypeB
的TypeB
我想得到'TypeA','TypeB'。
顺便说一下,这是我的表:
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
答案 0 :(得分:1)
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
模型非常难以管理。
您可能希望在我的博客中阅读这篇文章:
介绍了如何在adjacency list
中实现更简单的MySQL
模型。