链接列表表上的Oracle分层查询

时间:2013-04-12 13:31:15

标签: sql oracle hierarchical-data

我有下表实现链表。我想以rate_sequence_id为1开始查询,并获取链接到它的下一条记录,在这种情况下为30。因此查询应返回两行(rate_sequence_id为1和30)。

但是,以下查询要么只返回1行,要么返回“循环”错误,具体取决于CONNECT BY子句中的哪一列。

我试图用这些数据做什么?

SELECT * FROM TEST
CONNECT BY PRIOR RATE_SEQUENCE_ID = NEXT_RATE
START WITH RATE_SEQUENCE_ID = 1

测试数据:

CREATE TABLE TEST (
  RATE_SEQUENCE_ID      NUMBER(10,0),
  NEXT_RATE             NUMBER(10,0),
  DURATION              NUMBER,
  RATE                  NUMBER
);  


Insert into TEST (RATE_SEQUENCE_ID,NEXT_RATE,DURATION,RATE) values (50,51,28,0.99);
Insert into TEST (RATE_SEQUENCE_ID,NEXT_RATE,DURATION,RATE) values (51,51,112,9.99);
Insert into TEST (RATE_SEQUENCE_ID,NEXT_RATE,DURATION,RATE) values (1,30,28,0.99);
Insert into TEST (RATE_SEQUENCE_ID,NEXT_RATE,DURATION,RATE) values (30,30,112,14.99);
Insert into TEST (RATE_SEQUENCE_ID,NEXT_RATE,DURATION,RATE) values (0,0,0,0);
Insert into TEST (RATE_SEQUENCE_ID,NEXT_RATE,DURATION,RATE) values (31,0,30,0);

1 个答案:

答案 0 :(得分:1)

所以这是你的问题:

Insert into TEST (RATE_SEQUENCE_ID,NEXT_RATE,DURATION,RATE) values (30,30,112,14.99);

30与自身相连。这是对的还是错字?

如果该数据是正确的并且您使用的是现代版本的Oracle,则可以使用NOCYCLE子句从循环中逃脱。这绝对是10g(也许在9i,我的记忆在这里失败了)。 Find out more

SELECT * FROM TEST
CONNECT BY NOCYCLE PRIOR RATE_SEQUENCE_ID = NEXT_RATE
START WITH RATE_SEQUENCE_ID = 1