允许具有嵌套集结构的多个具有相同名称的类别

时间:2010-11-10 09:37:08

标签: mysql nested-sets

基于http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/,我已将类别层次结构更改为使用左右值。除了两个类别具有相同名称之外,这种方法很有效。

CREATE TABLE `nested_category` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(80) DEFAULT NULL,
  `lft` int(11) NOT NULL DEFAULT '0',
  `rgt` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=28 ;

INSERT INTO `nested_category` VALUES(2, 'Reviews', 3, 20);
INSERT INTO `nested_category` VALUES(6, 'Music2', 24, 25);
INSERT INTO `nested_category` VALUES(18, 'Culture', 2, 21);
INSERT INTO `nested_category` VALUES(19, 'Music', 18, 19);

然后:

SELECT node.name, (
COUNT( parent.name ) -1
) AS depth
FROM nested_category AS node, nested_category AS parent
WHERE node.lft
BETWEEN parent.lft
AND parent.rgt
GROUP BY node.name
ORDER BY node.lft
LIMIT 0 , 30

......给出:

name  depth 
Culture 0
Reviews 1
Music   2
Music2  0

......这是完美的。但是,如果我将“music2”改为“music”,我会得到:

name  depth 
Culture 0
Reviews 1
Music   3

关于如何保持嵌套深度正确但允许多个具有相同名称的类别的任何想法?

1 个答案:

答案 0 :(得分:0)

将ID添加到结果中,GROUP BY以保留选择的唯一性。

SELECT node.name, id, (
COUNT( parent.name ) -1
) AS depth
FROM nested_category AS node, nested_category AS parent
WHERE node.lft
BETWEEN parent.lft
AND parent.rgt
GROUP BY node.name, id
ORDER BY node.lft
LIMIT 0 , 30