如何递归填充子类别?

时间:2016-05-08 05:59:06

标签: mysql sql recursive-query

我有一张名为categories的表。

表结构如下:

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`)
);

表中有3种类型的项目:

  1. 主要类别(其parent_id为-1)
  2. 二级类别(其parent_id主要类别
  3. 第三级类别(其parent_id二级类别中的任何一种)
  4. 以下是一些示例数据:

    - 类别记录

    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
    

    感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

你可以尝试一下:

<process id="myProcess">
  <extensionElements>
    <activiti:potentialStarter>
       <resourceAssignmentExpression>
         <formalExpression>group(role1), user(kermit)</formalExpression>
        </resourceAssignmentExpression>
    </activiti:potentialStarter>
</extensionElements>

您将获得如下所示的输出结构:

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;

Reference