Oracle中的SQL Parent-Child在同一个表中

时间:2013-08-22 11:54:36

标签: sql oracle select parent-child

我需要了解如何使用以下示例。

假设我有这两个表:

    **Table Name: Children**
Child    Shirt_Color_ID    Parent
Bob           1             Kate
Kate          2             Jack
Jack          3             Jill
.             .              .
.             .              .

    **Table Name: Shirt_Colors**
Shirt_Color_ID    Shirt_Color 
      1              Red
      2              Blue
      3              White

我想返回下表:

Child   Child_Shirt_Color    Parent     Parent_Shirt_Color
Bob           Red             Kate           Blue

我如何获得Parent_Shirt_Color? 我得到了如何显示Child,Child_Shirt_Color,Parent:

select 
  Children.Child, 
  Shirt_Colors.Shirt_Color,
  Children.Parent
from
  Children,
  Shirt_Colors
where
  Shirt_Colors.Shirt_Color_ID = Children.Shirt_Color_ID and
  Children.Child =  'Bob';

我已经看过其他的例子,谈到使用“WITH”,但每次我尝试说它不受支持时都会出错。此外,我和父母之间的关系非常长,所以我不希望整个列表返回 - 只有2-3代。

使用Oracle

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

您需要CTE并将其用于递归查询。 http://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx

请尝试以下代码:

DROP TABLE Children
DROP TABLE Shirt_Colors

CREATE TABLE  Children(
    Child varchar(20),
    Shirt_Color_ID int,
    Parent varchar(20)
)

CREATE TABLE Shirt_Colors
(
    Shirt_Color_ID int,
    Shirt_Color varchar(20)
) 

INSERT INTO Shirt_Colors (Shirt_Color_ID, Shirt_Color)
VALUES  (1, 'Red'),
        (2, 'Blue'),
        (3, 'White'),
        (4, 'Yellow')
INSERT INTO Children (Child, Shirt_Color_ID, Parent)
VALUES  ('Bob', 1, 'Kate'),
        ('Kate', 2, 'Jack'),
        ('Jack', 3, 'Jill'),    
        ('Jill', 4, NULL)   

select * from Children
;       
WITH CTE (Child, Shirt_Color, Parent)
AS
(
    SELECT  
        C.Child, 
        SC.Shirt_Color,
        C.Parent
    FROM Children C
    INNER JOIN Shirt_Colors SC
    ON C.Shirt_Color_ID = SC.Shirt_Color_ID
    WHERE C.Parent IS NULL

    UNION ALL

    SELECT 
        C.Child,
        SC.Shirt_Color,
        C.Parent
    FROM CTE
    INNER JOIN Children C
    ON CTE.Child = C.Parent
    INNER JOIN Shirt_Colors SC
    ON C.Shirt_Color_ID = SC.Shirt_Color_ID
)   
SELECT 
    Child,
    Shirt_Color,
    Parent
FROM CTE