Oracle 9中的递归查询

时间:2014-05-01 17:09:57

标签: sql oracle oracle9i

我想写一个查询来计算某人和他的朋友之间的分离程度。我写了以下内容:

WITH CTE AS (
    SELECT UserFriends.PlayerID AS PlayerID, UserFriends.FriendsWith AS Friend, 
                   1 AS Distance 
            FROM UserFriends WHERE UserFriends.PlayerID = 1
    UNION ALL
    SELECT CTE.PlayerID, UserFriends.FriendsWith AS Friend, 
                   CTE.Distance + 1 AS Distance 
            FROM UserFriends 
            INNER JOIN CTE ON UserFriends.PlayerID = CTE.Friend
) 
SELECT PlayerID, Friend, Distance FROM CTE;

但是我收到一条错误消息:

Error: ORA-32031: illegal reference of a query name in WITH clause

似乎这种类型的递归查询仅在版本11g R2中引入。如果是这样,我怎样才能在版本9.2中获得相同的结果?

编辑:

我重新编写了如下查询:

INSERT INTO Degrees_Separation
   SELECT PlayerID, FriendsWith, LEVEL AS Degree
      FROM UserFriends
      START WITH PlayerID = 1
      CONNECT BY FriendsWith = PRIOR PlayerID
      AND LEVEL <= 10
      AND PRIOR DBMS_RANDOM.VALUE != DBMS_RANDOM.VALUE;

SELECT DISTINCT * FROM Degrees_Separation
WHERE PlayerID = 1;

以下是UserFriends的内容:

PLAYERID    FRIENDSWITH
1   2
1   3
1   8
1   12
2   1
2   4
2   7
2   9
2   15

结果不是我的预期。对于PlayerID = 1,我只看到FriendsWith为2,3,8和12的记录,即PlayerID 1的直接朋友

PLAYERID    FRIENDSWITH DEGREE
1   2   1
1   2   3
1   2   5
1   2   6
1   2   7
1   2   8
1   2   9
1   2   10
1   3   1
1   3   3
1   3   5
1   3   6
1   3   7
1   3   8
1   3   9
1   3   10
1   8   1
1   8   3
1   8   5
1   8   7
1   8   8
1   8   9
1   8   10
1   12  1
1   12  3
1   12  5
1   12  6
1   12  7
1   12  8
1   12  9
1   12  10

0 个答案:

没有答案