2011-03-16 234 views
1

我希望得到您對我想要做的遞歸查詢的幫助。 我在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]其中,路由字段是由來自都柏林的每條連接路徑中訪問的 機場構建的字符串。這是由' - '字符分隔的一系列機場名稱 。但是,取代整個機場名稱,只需顯示第一個 三個字符,以便每個字符串看上去都像 Dub> Sch> Dub> Sma> Sch> Dub> Sma> Cla> Mos。 屬性'路線'的類型應該是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; 

難道是正確的,如果是,我該怎麼辦呢?

+0

什麼我可以做的輸出。我必須創建一個新表格? – dali1985 2011-03-16 08:31:34

回答

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; 
+0

是的,這正是我想要的。非常感謝你。還有一個問題。你知道我怎麼修改查詢來選擇那些通過Clacton的路線? – dali1985 2011-03-16 08:48:21

+0

...從開始,目的地的'Clacton'的路徑[btw .: dep(出發)和arr(到達)是開始和目的地的更合適的術語] – 2011-03-16 08:55:43