我有这张桌子:
CREATE TABLE `categories` (
`id` int(11) NOT NULL auto_increment,
`category_id` int(11) default NULL,
`root_id` int(11) default NULL,
`name` varchar(100) collate utf8_unicode_ci NOT NULL,
`lft` int(11) NOT NULL,
`rht` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `category_id` (`category_id`),
KEY `lft` (`lft`,`rht`),
KEY `root_id` (`root_id`)
)
基于这个问题: Getting a modified preorder tree traversal model (nested set) into a <ul>
不同之处在于我在一张桌子上有很多树。每行都有一个外键,表示其父级和顶级父级:category_id 和 root_id。我也有基于此示例的 lft 和 rht 字段:http: //articles.sitepoint.com/article/hierarchical-data-database/2
基于此行:
INSERT INTO `categories` VALUES(1, NULL, NULL, 'Fruits', 1, 14);
INSERT INTO `categories` VALUES(2, 1, 1, 'Apple', 2, 3);
INSERT INTO `categories` VALUES(3, 1, 1, 'Orange', 4, 9);
INSERT INTO `categories` VALUES(4, 3, 1, 'Orange Type 1', 5, 6);
INSERT INTO `categories` VALUES(5, 3, 1, 'Orange Type 2', 7, 8);
INSERT INTO `categories` VALUES(6, 1, 1, 'Pear', 10, 11);
INSERT INTO `categories` VALUES(7, 1, 1, 'Banana', 12, 13);
INSERT INTO `categories` VALUES(8, NULL, NULL, 'Eletronics', 1, 14);
INSERT INTO `categories` VALUES(9, 8, 8, 'Cell Phones', 2, 3);
INSERT INTO `categories` VALUES(10, 8, 8, 'Computers', 4, 9);
INSERT INTO `categories` VALUES(11, 10, 8, 'PC', 5, 6);
INSERT INTO `categories` VALUES(12, 10, 8, 'MAC', 7, 8);
INSERT INTO `categories` VALUES(13, 8, 8, 'Printers', 10, 11);
INSERT INTO `categories` VALUES(14, 8, 8, 'Cameras', 12, 13);
如何构建代表这棵树的有序列表?
使用下面的sql:
SELECT c. * , (COUNT( p.id ) -1) AS depth
FROM `categorias` AS p
CROSS JOIN categories AS c
WHERE (
c.lft
BETWEEN p.lft
AND p.rht
)
GROUP BY c.id
ORDER BY c.lft;
我得到了这个结果:
如您所见,我也需要按 root_id 排序,以便生成正确的树。
另外,在得到树之后,有没有办法按名称对每个节点进行排序?