Logicalj
Logicalj

Reputation: 99

MySQL Query for Parent Child relationship

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.

Upvotes: 1

Views: 2962

Answers (2)

Rohit
Rohit

Reputation: 11

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

Upvotes: 1

Muhammad Raheel
Muhammad Raheel

Reputation: 19882

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;

Upvotes: 2

Related Questions