Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query for Parent Child Relationship

I have db table with parent child relationship as:

NodeId    NodeName    ParentId
------------------------------
1         Node1       0
2         Node2       0
3         Node3       1
4         Node4       1
5         Node5       3
6         Node6       5
7         Node7       2

Here parentId = 0 means that it is a root level node. Now I want to write an SQL Query which will return child at all level of a parent category.

e.g. for nodeId = 1, it should return 3, 4, 5, 6.

I am using MS SQL Server 2005

like image 523
Programmer Avatar asked Oct 16 '08 03:10

Programmer


People also ask

How do you query a parent-child relationship in SQL?

To find out who that child's parent is, you have to look at the column parent_id , find the same ID number in the id column, and look in that row for the parent's name. In other words, Jim Cliffy has no parents in this table; the value in his parent_id column is NULL .

How do I get all parent children in SQL?

parent = c. child ) SELECT distinct parent, child , level FROM cte order by level, parent; This will give you all descendants and the level.

What is parent/child relationship in database?

In database management, a relationship between two files. The parent file contains required data about a subject, such as employees and customers. The child is the offspring; for example, an order is the child to the customer, who is the parent.

What is parent table and child table in SQL?

The referenced table is called the parent table while the table with the foreign key is called the child table. The foreign key in the child table will generally reference a primary key in the parent table. A foreign key can be created using either a CREATE TABLE statement or an ALTER TABLE statement.


2 Answers

with [CTE] as (
    select * from [TheTable] c where c.[ParentId] = 1
    union all
    select * from [CTE] p, [TheTable] c where c.[ParentId] = p.[NodeId]
)
select * from [CTE]
like image 51
yfeldblum Avatar answered Oct 15 '22 07:10

yfeldblum


You should look into using the Nested Set Model for parent-child relationships within an SQL database. It's much nicer than trying to store the parentID of records in the table like this, and makes queries like this much easier.

like image 32
Keith Palmer Jr. Avatar answered Oct 15 '22 08:10

Keith Palmer Jr.