0

I need held understanding how to work with the following example.

Let's say I have these two tables:

    **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

And I want to return a following table:

Child   Child_Shirt_Color    Parent     Parent_Shirt_Color
Bob           Red             Kate           Blue

How would I get the Parent_Shirt_Color in? I got how to show 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';

Other examples I have looked at for this, talked about using "WITH," but get errors every time I try saying it is unsupported. Also, I have a very very long relation between parents and children, so I do not want the entire list returned - only 2-3 generations.

Using Oracle

Any help would be appreciated. Thanks!

4

1 回答 1

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
于 2013-08-22T12:31:05.640 回答