2017-09-21 4 views
-3

私はテーブルがnレベルの親子関係を表しています。SQL get multiply子要素

ParentID ChildID 
1 A  B 
2 B  C 
3 B  D 
3 C  E 
...... 

私は親ID Aを持っている場合は、どのように私はSQL文でE、すべてのA、B、C、Dを持っています(すべての要素を仮定すると、子どもたち/秒を持つことができるので、必要に応じていくつかの再帰があるかもしれません) 。

+1

予想される出力は? – Ravi

+0

あなたはどのデータベースを使用していますか?具体的にご記入ください – Squirrel

+0

A(この場合はA、B、C、D、E)に関連するすべてのIDを選択します。私はMS SQLサーバーを使用しています。ありがとう! – DennisL

答えて

0

好きな音は再帰的な共通テーブル式(CTE)です。階層を抽出するのは良いことです。

このリンクは役立ちます:MSDN Recursive Queries Using Common Table Expressions そして私は以下の主な例をコピーしました。

USE AdventureWorks2008R2; 
GO 
WITH DirectReports (ManagerID, EmployeeID, Title, DeptID, Level) 
AS 
(
-- Anchor member definition 
    SELECT e.ManagerID, e.EmployeeID, e.Title, edh.DepartmentID, 
     0 AS Level 
    FROM dbo.MyEmployees AS e 
    INNER JOIN HumanResources.EmployeeDepartmentHistory AS edh 
     ON e.EmployeeID = edh.BusinessEntityID AND edh.EndDate IS NULL 
    WHERE ManagerID IS NULL 
    UNION ALL 
-- Recursive member definition 
    SELECT e.ManagerID, e.EmployeeID, e.Title, edh.DepartmentID, 
     Level + 1 
    FROM dbo.MyEmployees AS e 
    INNER JOIN HumanResources.EmployeeDepartmentHistory AS edh 
     ON e.EmployeeID = edh.BusinessEntityID AND edh.EndDate IS NULL 
    INNER JOIN DirectReports AS d 
     ON e.ManagerID = d.EmployeeID 
) 
-- Statement that executes the CTE 
SELECT ManagerID, EmployeeID, Title, DeptID, Level 
FROM DirectReports 
INNER JOIN HumanResources.Department AS dp 
    ON DirectReports.DeptID = dp.DepartmentID 
WHERE dp.GroupName = N'Sales and Marketing' OR Level = 0; 
GO