Lets assume I have this sample data:
| Name | ID | PARENT_ID | ----------------------------- | a1 | 1 | null | | b2 | 2 | null | | c3 | 3 | null | | a1.d4 | 4 | 1 | | a1.e5 | 5 | 1 | | a1.d4.f6 | 6 | 4 | | a1.d4.g7 | 7 | 4 | | a1.e5.h8 | 8 | 5 | | a2.i9 | 9 | 2 | | a2.i9.j10| 10 | 9 |
I would like to select all records start from accountId = 1, so the expected result would be:
| Name | ID | PARENT_NAME | PARENT_ID | ------------------------------------------- | a1 | 1 | null | null | | a1.d4 | 4 | a1 | 1 | | a1.e5 | 5 | a1 | 1 | | a1.d4.f6 | 6 | a1.d4 | 4 | | a1.d4.g7 | 7 | a1.d4 | 4 | | a1.e5.h8 | 8 | a1.e5 | 5 |
I am currently able to make the recursive select, but then I can't access the data from the parent reference, hence I can't return parent_name. The code I'm using is (adapted to the simplistic example):
SELECT id, parent_id, name FROM tbl START WITH id = 1 CONNECT BY PRIOR id = parent_id
What SQL should I be using to the mentioned above retrieval?
Additional key words for future seekers: SQL to select hierarchical data represented by parent keys in same table
with r ( empno, mgr ) as ( select empno, mgr -- ANCHOR leg of recursive query from scott. emp where empno = 7499 union all select e. empno, e. mgr -- RECURSIVE leg of recursive query from scott.
Thus, a recursive CTE consists of a nonrecursive SELECT part followed by a recursive SELECT part. Each SELECT part can itself be a union of multiple SELECT statements. The types of the CTE result columns are inferred from the column types of the nonrecursive SELECT part only, and the columns are all nullable.
Recursion is achieved by WITH statement, in SQL jargon called Common Table Expression (CTE). It allows to name the result and reference it within other queries sometime later. Here is a sample. Query (SELECT 1 AS n) now have a name — R .
Recursion is implemented in standard SQL-99 using common table expressions (CTEs). DB2, Microsoft SQL Server, Oracle and PostgreSQL all support recursive queries using CTEs.
What about using PRIOR,
so
SELECT id, parent_id, PRIOR name FROM tbl START WITH id = 1 CONNECT BY PRIOR id = parent_id`
or if you want to get the root name
SELECT id, parent_id, CONNECT_BY_ROOT name FROM tbl START WITH id = 1 CONNECT BY PRIOR id = parent_id
Use:
SELECT t1.id, t1.parent_id, t1.name, t2.name AS parent_name, t2.id AS parent_id FROM tbl t1 LEFT JOIN tbl t2 ON t2.id = t1.parent_id START WITH t1.id = 1 CONNECT BY PRIOR t1.id = t1.parent_id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With