I have SQL Server table structure like below:
ID Name ParentID
-----------------------
1 Root NULL
2 Business 1
3 Finance 1
4 Stock 3
I want to display the details in my web page like
ID Name ParentName
-------------------------
1 Root -
2 Business Root
3 Finance Root
4 Stock Finance
How can I construct my SQL query?
8条答案
按热度按时间gpnt7bae1#
try this...
With the left join, the query will not find anything to join for the NULL and return blank for the
ParentName
column.EDIT:
If you do not want the 'Parent' column to be blank, but want to show a '-' dash then use this query.
gcuhipw92#
Assuming SQL Server 2005+, use a recursive CTE like this:
The CASTing of the NULL might look odd, but SQL Server defaults the data type to INT unless specified in a manner like you see in my query.
1yjd4xko3#
I am facing same situation. I want to fetch all child list of particular parent from same table, where as MySQL is not provided Recursive CTE in below MySQL 8.
I had resolved my issue with recursive store procedure. In that we need to set max_sp_recursion_depth to recursive store procedure call.
My table structure is below
My store procedure(With recursion) is below:
To Call this stored procedure we need to pass 3 arguments,
CALL getAllChilds(1,@ids,']');
Using this store procedure you may get all level child in JSON string. You can parse this json string and convert in any OBJECT using any JSONparser.
Or
we can wrap this answer in store procedure for use it into any programming language like JAVA. we are wrapping this into store procedure because we can't use := in query. Here we are using find_in_set function. My store procedure(Without recursion).
To call this store procedure we need just parent Id.
nwwlzxa74#
tct7dpnv5#
I think the following query would work. I've not tested it.
Basically, what I'm doing is doing is choosing parent information, and relating it to each tuple.
nkhmeac66#
Like someone posted earlier, it needs to be a recursive function. There can be multiple scenarios - One Parent to Multiple Child (Level 1 Hierarchy) Parent 1 has Child 1 Parent 1 has Child 2 Child to Multiple Child (Level 2 Hierarchy) And so on.
My example has parent curve id and child curve id. For example,
relj7zay7#
This is a simple way:
zpgglvta8#
For Mysql just incase someone needs