1

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

| 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....

谢谢。

4

2 回答 2

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;
于 2013-01-04T07:44:12.303 回答
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
于 2014-04-09T07:17:35.587 回答