MySQL查询父子关系

时间:2013-01-04 07:34:34

标签: mysql

我想编写一个select查询来获取从子级到父级的完整路径:

| Unique Id | Child Code | Parent Code |
|     X     |     9      |     7       |
|     Y     |     7      |     6       |
|     Z     |     6      |     5       |
|     A     |     5      |    NULL     |
|     B     |     11     |     33      |
|     C     |     33     |     22      |
|     D     |     22     |    NULL     |

如果选择的代码是9,则查询应返回其所有父项,结果如下:9-7-6-5 ......

如果选择的代码是11,则查询应返回:11-33-22 ....

感谢。

2 个答案:

答案 0 :(得分:2)

尝试此查询

SELECT *
FROM (
    SELECT
        @r AS _id,
        (SELECT @r := parent_code FROM mytable WHERE unique_id = _id) AS parent_id,
        @l := @l + 1 AS lvl
    FROM
        (SELECT @r := 9, @l := 0) vars,
        mytable m
    WHERE @r <> 0) T1
JOIN mytable T2
ON T1._id = T2.id
ORDER BY T1.lvl DESC;

答案 1 :(得分:1)

使用NULL父值:

SELECT *
FROM <table_name>
ORDER BY COALESCE(<parent_id>,<id>), <id>), category_parent_id IS NOT NULL

使用ZERO父值:

SELECT *
FROM <table_name>
ORDER BY COALESCE((SELECT NULLIF(<parent_id>,0)), <id>), NULLIF(<parent_id>,0) IS NOT NULL