我想在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
答案 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;