MySQL树从路径

时间:2015-10-20 05:40:36

标签: mysql

我想在MYSQL中使用此引用

显示树结构
+----+--------------+----------------+
| id |  name        | Path           |
| 751| ledger 1     |   751/         |
| 752| l sub        |   751/752/     |
| 753| l sub1.2     |   751/752/753/ |
| 754| l sub2       |   751/754/     |
| 756| l Sub1.3     |   751/752/756/ |
| 757| l Sub2.1     |   751/754/757/ |
+----+--------------+----------------+

我只需要答案

ledger 1
     l sub
         l sub1.2
         L Sub1.3
     l sub2 
         l Sub2.1

1 个答案:

答案 0 :(得分:2)

您可以在名称之前尝试连接空格:

SELECT
  CASE  LENGTH(Path) - LENGTH(REPLACE(Path, '/', '')) 
    WHEN 2 THEN CONCAT('   ', name)
    WHEN 3 THEN CONCAT('      ', name)
    WHEN 4 THEN CONCAT('         ', name)
    WHEN 5 THEN CONCAT('            ', name)
    WHEN 6 THEN CONCAT('               ', name)
    -- ... to max depth
    ELSE name
  END AS result
FROM tab
ORDER BY path;

SqlFiddleDemo

修改

使用REPEAT

SELECT
  CASE  
    WHEN LENGTH(Path) - LENGTH(REPLACE(Path, '/', '')) > 1 
    THEN CONCAT(REPEAT('    ', LENGTH(Path) - LENGTH(REPLACE(Path, '/', ''))-1 ),name)
    ELSE name
  END AS result
FROM tab
ORDER BY path;

SqlFiddleDemo

另一种方法(在评论中提出@Mchl)是计算DEPTH并在应用程序中进行格式化:

SELECT *,
   LENGTH(Path) - LENGTH(REPLACE(Path, '/', '')) AS depth
FROM tab
ORDER BY path;