递归查询

时间:2011-03-16 08:16:02

标签: database db2 recursive-query

我希望您对我想要做的递归查询有所帮助。 我在DB2中创建了这个表:

connect reset;
connect to sample;
DROP TABLE FLIGHTS;

CREATE TABLE FLIGHTS
 (START         VARCHAR(16)     NOT NULL,
  DESTINATION   VARCHAR(16)     NOT NULL,
  DISTANCE  BIGINT          NOT NULL    
 );
insert into FLIGHTS values ('Dublin','Bhogrol',5340);
insert into FLIGHTS values ('Dublin','Smallville',5500);
insert into FLIGHTS values ('Smallville','Seattle',1300);
insert into FLIGHTS values ('Smallville','Clacton',6700);
insert into FLIGHTS values ('Bhogrol','Moscow',2320);
insert into FLIGHTS values ('Moscow','Seattle',3600);
insert into FLIGHTS values ('Bhogrol','Smallville',2950);
insert into FLIGHTS values ('Rome','Bhogrol',720);
insert into FLIGHTS values ('Clacton','Moscow',6700);
insert into FLIGHTS values ('Rome','Smallville',3050);
insert into FLIGHTS values ('Schippol','Smallville',8990);
insert into FLIGHTS values ('Seattle','Schippol',7840);
insert into FLIGHTS values ('Bhogrol','Clacton',1300);
insert into FLIGHTS values ('Bilbao','Moscow',1270);
insert into FLIGHTS values ('Smallville','Schippol',8990);

我想找到来自都柏林的所有相关航班少于8个 停止。查询的输出应该是一组包含以下3字段的行 格式:[route,distance,stops]其中route字段是从中构建的字符串 从都柏林到每个相连路径的机场。这是一系列机场名称 以' - '字符分隔。但是,而不是整个机场名称,只显示第一个 三个字符,这样每个字符串看起来像 例如,Dub< Sch> Dub> Sma> Sch> Dub> Sma> Mos>。 属性“route”的类型应为VARCHAR(40)。

我想以这种方式开始:

WITH path (start, destination, distance, stops)
AS(
  SELECT f.start, f.destination, f.distance, 0
  FROM flights f
  WHERE start = 'Dublin'
  UNION ALL
  SELECT p.start, f.destination,
  p.distance + f.distance, p.stops+1
  FROM flights f, path p
  WHERE p.destination = f.start AND p.stops < 8 
)
SELECT start, destination, distance, stops 
FROM path;

是否正确?如果是,我该怎么办?

1 个答案:

答案 0 :(得分:3)

我认为你正在寻找这样的东西:

WITH path (route, start, destination, distance, stops)
AS
(
  SELECT substr(f.start,1,3) || ' > '|| substr(f.destination,1,3) as route,
         f.start, 
         f.destination,
         f.distance, 
         0
  FROM flights f
  WHERE start = 'Dublin'
  UNION ALL
  SELECT p.route || ' > ' || substr(f.destination,1,3) as route,
         f.start,
         f.destination,
         p.distance + f.distance, 
         p.stops + 1
  FROM flights f
    JOIN path p ON p.destination = f.start AND p.stops < 8 
)
SELECT route, distance, stops 
FROM path;