I need a sql or hql query to find all parents of a particular record, that should work in oracle as well as mysql, for eg if I have the id: 201, the parents would be: 188, 187, 1.
any help would be greatly appreciated, thanks
SQL or HQL Query – How to Find All Parents of a Particular Record
cteMySQLoracleoracle-sql-developer
Related Question
- Mysql – To find out the sum total of GRNQty and GRNValue of particular item from column 1
- MySQL – How to Generate All Combinations Between Two Columns
- Oracle – Query to join fact table to bridge table and show bridge group rows in one row
- Oracle – How to Find All Unique Columns That Are Allowed Null
- Oracle – Apply SQL to all schema in database
- MySQL – How to Query All Entities Associated with All Children Recursively
- Mysql – Locating all records relevant for a specific date
- PL/SQL – Query to Find All Dates Between Two Specified Dates
Best Answer
On Oct 24, 2011, I wrote some Stored Functions to perform Ancestor and Descendant traversals (Find highest level of a hierarchical field: with vs without CTEs ). From my post, you would use
GetAncestry
. From your data, the code inGetAncestry
will traverse until it sees-1
as a parent id. No changes in the algorithm are needed except to changeparent_id
toparent
.For the sake of example, let's suppose the table is called
mydb.mytable
GetAncestry Code
Once you create this stored procedure, you would call the function as follows:
Let's test that out
Sample Data Based On Your Question
Load Sample Data
Create the Stored Function
Call GetAncestry
Only one thing left to do...
GIVE IT A TRY !!!
I have discussed using GetAncestry in the DBA StackExchange many times
Please note that this is a MySQL-specific answer. Please read PL/SQL Documentation if you wish to implement the algorithm in a PL/SQL block or a Stored Procedure.