如何递归填充子类别?

How to recursively populate sub-categories?

我有一个名为 categories 的 table。

table结构如下:

DROP TABLE IF EXISTS `categories`;
CREATE TABLE `categories` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(100) CHARACTER SET utf8 NOT NULL,
  `parent_id` int(11) NOT NULL DEFAULT '-1',
  PRIMARY KEY (`ID`)
);

table中有 3 种类型的项目:

  1. 主要类别parent_id为-1)
  2. 二级类别(其parent_id是任何主要类别
  3. 第三级类别(其parent_id是任何第二级类别

下面是一些示例数据:


-- 分类记录


INSERT INTO `categories` VALUES ('1', 'A', '-1');
INSERT INTO `categories` VALUES ('2', 'B', '-1');
INSERT INTO `categories` VALUES ('3', 'C', '-1');
INSERT INTO `categories` VALUES ('4', 'a', '1');
INSERT INTO `categories` VALUES ('5', 'b', '2');
INSERT INTO `categories` VALUES ('6', 'c', '3');
INSERT INTO `categories` VALUES ('7', 'aa', '4');
INSERT INTO `categories` VALUES ('8', 'bb', '5');
INSERT INTO `categories` VALUES ('9', 'cc', '6');
INSERT INTO `categories` VALUES ('10', 'ccc', '6');

我想得到如下所示的输出结构:

Main Category      Second Level Category        Third Level Category
A                           a                           aa
B                           b                           bb
C                           c                           cc
C                           c                           ccc

感谢任何帮助。

你可以试试看:

SELECT 
t1.title AS 'Main Category',
t2.title AS 'Second Level Category',
t3.title AS 'Third Level Category'
FROM categories AS t1
INNER JOIN categories AS t2 ON t2.parent_id = t1.ID
INNER JOIN categories AS t3 ON t3.parent_id = t2.ID;

您将获得如下输出结构:

Main Category      Second Level Category        Third Level Category
A                           a                           aa
B                           b                           bb
C                           c                           cc
C                           c                           ccc

Reference