MySQL查询:同一个表上的多级别类别

时间:2017-07-27 14:42:59

标签: mysql

好日子的地球人,

这是我的表结构

acctCode| refAcctCode | acctName
------    ----------    --------
 AC001                    SALES
 AC002                    AR
 AC003     AC001          FURNITURE
 AC004     AC003          OFFICE FURNITURE
 AC005     AC002          INVOICE
 AC006     AC001          UTILITIES

和预期的输出将是

SALES
    FURNITURE
        OFFICE FURNITURE
    UTILITIES
AR
    INVOICE
然而,它不仅限于3级,而且限于第n次

例如:

Parent1
  Child1
    child1.1
      child1.1.1
        child1.1.1.1
  child2
  child3
  child3

parent2
  child1
  child2
  child3

鉴于表格结构格式,我如何查询以获得该输出?

感谢

1 个答案:

答案 0 :(得分:0)

以下是基于用户定义过程的解决方案:

CREATE PROCEDURE list()
BEGIN
 DROP TABLE IF EXISTS tmp; -- for collecting the records
 CREATE TABLE tmp (id varchar(1024), name varchar(128));
 SET @i=-5; SET @s=0;      -- @i: offset for id comparison
                           -- @s: space padding for name column
 INSERT INTO tmp           -- fill in entries without refAcctCode
 SELECT a.acctCode, a.acctName FROM tbl a WHERE a.refAcctCode is null;

                           -- do as often as necessary ...    
 WHILE ROW_COUNT() > 0 DO 
  SET @i=@i+6; SET @s=@s+2;-- increment variables
  INSERT INTO tmp
  SELECT CONCAT(id,' ',a.acctCode), CONCAT(SPACE(@s),a.acctName) 
  FROM tbl a INNER JOIN tmp b ON SUBSTR(id,@i)=a.refAcctCode;
 END WHILE;

 SELECT * FROM tmp ORDER BY id;  -- list the consolidated temp. table
END;

执行
CALL list()

您将获得以下输出:

    id                name
------------------------------------------
1   AC001             SALES
2   AC001 AC003         FURNITURE
3   AC001 AC003 AC004     OFFICE FURNITURE
4   AC001 AC006         UTILITIES
5   AC002             AR
6   AC002 AC005         INVOICE

您可以在此处找到有效的演示:http://rextester.com/ZRXN57872

我使用空格作为accName列的前缀。这样可以更轻松地查看结果列表中的类别级别。请随意使用该程序,使其符合您的特定需求。