MYSQL子查询获取父路径

时间:2014-03-07 04:50:20

标签: mysql recursion path subquery parent

我希望得到我记录的所有路径。 使用MYSQL递归,子查询,而不使用Procedure /,函数

这是我的表vw_dir

+--------+--------+----------+
| dir_id | parent | dir_name |
+--------+--------+----------+
|      2 |      1 | dir1     |
|      5 |      1 | dir2     |
|      3 |      2 | dir3     |
|      4 |      3 | dir4     |
|      1 | NULL   | root     |
+--------+--------+----------+

现在我想获取每条记录的路径......示例

+--------+--------+----------+----------------------+
| dir_id | parent | dir_name |   path               |       
+--------+--------+----------+----------------------+
|      2 |      1 | dir1     | /root/dir1           | 
|      5 |      1 | dir2     | /root/dir2           |
|      3 |      2 | dir3     | /root/dir1/dir3      |
|      4 |      3 | dir4     | /root/dir1/dir3/dir4 |
|      1 | NULL   | root     | /root                |
+--------+--------+----------+----------------------+

这是我现有的代码

SELECT @id:=main_dir as dir_id, main_dir.parent, main_dir.dir_name
    (SELECT GROUP_CONCAT(path) FROM (
    SELECT  @r AS _dirid, ( SELECT  @r := parent FROM vw_dir
    WHERE   dir_id = _dirid ) AS parent, (SELECT dir_name FROM vw_dir WHERE dir_id = _dirid) path , @l := @l + 1 AS lvl
    FROM  ( SELECT  @r := @id, @l := 0) vars, vw_dir d1
            WHERE  @r IS NOT NULL ORDER BY lvl DESC
    ) qi) as path FROM vw_dir main_dir.

0 个答案:

没有答案