1

I want to write a select query to get the complete path from child to parent as:

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

if code selected is 9 then query should return its all the parents as result which are : 9-7-6-5....

and if code selected is 11 then query should return: 11-33-22....

Thanks.

Logicalj
  • 99
  • 3
  • 14

2 Answers2

2

Try this query

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;
Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103
1

With NULL Parent Value:

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

With ZERO Parent Value:

SELECT *
FROM <table_name>
ORDER BY COALESCE((SELECT NULLIF(<parent_id>,0)), <id>), NULLIF(<parent_id>,0) IS NOT NULL
Carl0s1z
  • 4,683
  • 7
  • 32
  • 47
Rohit
  • 11
  • 1