2

Possible Duplicate:
How to store directory / hierarchy / tree structure in the database?

I use this query:

SELECT Id, Name, ParentId
FROM Table_1

And then I build the tree using all elements.

But what if I want to build a tree that starts from definite Id, so I need to make a query that returns only this Id and all childs of this Id Like this:

SELECT Id, Name, ParentId
FROM Table_1
WHERE (Id = randomNumber) OR (all possible childs of Id = randomNumber)

Help me please to make a query.

EDIT:

This is how you can make it in Oracle

SELECT Id, Name, ParentId
FROM table_1
Connect by prior Id = ParentId
Start with Id = randomNumber

I need MS-Access

Community
  • 1
  • 1
Steven
  • 185
  • 1
  • 5
  • 11

4 Answers4

1

Try this one, I hope this is what you are looking for:

DECLARE @ID int

SET @ID = 1;

WITH CTE_Table_1
(
 ID,
 Name,
 ParentID,
 TreeLevel
)
AS(
  SELECT 
   ID,
   Name,
   ParentID,
   0 AS TreeLevel
  FROM Table_1
  WHERE ID = @ID

  UNION ALL

  SELECT 
   T.ID,
   T.Name,
   T.ParentID,
   TreeLevel + 1
  FROM Table_1 T
  INNER JOIN CTE_Table_1 ON CTE_Table_1.ID = T.ParentID
)

SELECT * FROM CTE_Table_1
András Ottó
  • 7,605
  • 1
  • 28
  • 38
0

You can join the table on itself linking the parent id to the child id

SELECT T1.Id, T1.Name, T2.Id, T2.Name
FROM   Table_1 as T1
JOIN   Table_1 as T2 on T1.Id = T2.ParentId

Given the data

Id, Name       ParentId
1,  Top,        null
2,  ChildOne,   1
3,  ChildTwo,   1
4,  ChildThree, 1

This will give you a result like

1,   Top,    2, ChildOne
1,   Top,    3, ChildTwo
1,   Top,    4, ChildFour
Ian Quigley
  • 500
  • 1
  • 6
  • 22
0

You are almost there, this should do the trick

SELECT Id, Name, ParentId 
FROM Table_1 
WHERE (Id = randomNumber) OR (ParentId = randomNumber) 
Stuart
  • 1,123
  • 8
  • 24
0

As noted on the related post, this cannot be done using SQL alone, however it can be done using a combination of SQL and VBA relatively easy.

The goal is for a specified Id to return that record and all of its children. As a result, all you need is a boolean function which returns true when the row Id is a direct descendant of the specified ancestor.

Your SQL would be:

SELECT Id, Name, ParentId
FROM Table_1
WHERE IsDescendant(Id, randomNumber);

The VBA function in Access would be:

Public Function IsDescendant(id As Integer, relative As Integer) As Boolean
    Dim currentID As Variant
    currentID = id

    Do Until IsNull(currentID)
        If (currentID = relative) Then
            IsDescendant = True
            Exit Function
        End If
        currentID = DLookup("ParentId", "Table_1", "Id=" & currentID)
    Loop
    IsDescendant = False
End Function

Performance-wise this may not be the greatest because I used DLookup but we could also use RecordSet objects if there are significant performance gains to be had. This is just the quickest code I could jot down.

nicholas
  • 2,969
  • 20
  • 39