SQL to create a hierarchical result-set

38 Views Asked by At

I have a customer table, with an ID column and a parentId column. Whereby the parentId is a FK to the ID of another customer.

Due to the FK, the ROOT customer is a parent of itself.

With the following SQL I am attempting to create a hierarchical result-set - but it is not working.

It is giving me a never-ending cascade (2001 rows), despite only having 2 customers in the table, where one is a parent and one is a child... and so I was expecting to receive ONLY 2 rows in total.

WITH RECURSIVE CustomerTree AS (
        SELECT id as customerId, displayName, IFNULL(customerParentId,0) AS customerParentId, 1 as customerlevel
        FROM customer c1 WHERE c1.id = 1

        UNION ALL

        SELECT c2.id as customerId, c2.displayName, c2.customerParentId, ct.customerlevel + 1 as customerlevel
        FROM customer c2
        INNER JOIN CustomerTree ct ON c2.customerParentId = ct.customerId
    )
    SELECT customerId, displayName, customerParentId, customerlevel
    FROM CustomerTree
    ORDER BY customerlevel, displayName;

results:

"customerId"    "displayName"    "customerParentId"    "customerlevel"
"1"    "PARENT_CO"    "1"    "1"
"23"    "CHILD_CO"    "1"    "2"
"1"    "PARENT_CO"    "1"    "2"
"23"    "CHILD_CO"    "1"    "3"
"1"    "PARENT_CO"    "1"    "3"
"23"    "CHILD_CO"    "1"    "4"
"1"    "PARENT_CO"    "1"    "4"
"23"    "CHILD_CO"    "1"    "5"
"1"    "PARENT_CO"    "1"    "5"
"23"    "CHILD_CO"    "1"    "6"
"1"    "PARENT_CO"    "1"    "6"
"23"    "CHILD_CO"    "1"    "7"
...
...

I would really appreciate any thoughts you might have. Thanks.

0

There are 0 best solutions below