允许具有嵌套集合结构的多个同名类别
基于 http://mikehillyer.com/articles/managing-hierarchical-data-在-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
关于如何保持嵌套深度正确,但允许多个类别具有相同名称的任何想法?
Based on http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/, I've changed my category hierarchy to use left and right values. This works great, except for when two categories have the same name.
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);
And then:
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
... gives:
name depth
Culture 0
Reviews 1
Music 2
Music2 0
... which is perfect. But, if I change "music2" to "music", I get:
name depth
Culture 0
Reviews 1
Music 3
Any ideas as to how I can keep the nesting depth correct, but allow multiple categories with the same name?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将 id 添加到结果和
GROUP BY
以保留您选择的唯一性。Add the id to the result and
GROUP BY
to retain the uniqueness of your select.