我需要使用视图从传输数据库中找到行程详细信息。
我怎么也做不到。我需要进行查询,查找所有不超过2条腿的行程,即1个或2个目的地的行程,并显示行程编号(TripNo),行程起点(开始),第一个目的地(Stop1)和第二个目的地(Stop2)格式如下。
TripNo START STOP1 STOP2
- - - - - - - - - - - - - - - -
05 CatmanSt Chinatwon MayflowerSt
03 MayflowerSt Auckland
这是下表。
TRIP( TripNo,LicenseCardNo,CarReg,TRIP_DATE,)
PRIMARY KEY (TripNo),
FOREIGN KEY (LicenseCardNo) REFERENCES DRIVER(LicenseCardNo),
FOREIGN KEY (CarReg) REFERENCES TRUCK(CarReg)
( 1, DR1, 'SJG123', ADD_MONTHS(TRUNC(SYSDATE),0)-135 )
( 2, DR2, 'GBC222', ADD_MONTHS(TRUNC(SYSDATE),0)-135 )
( 3, DR1, 'GBC270', ADD_MONTHS(TRUNC(SYSDATE),0)-133 )
( 4, DR3, 'SJG123', ADD_MONTHS(TRUNC(SYSDATE),0)-130 )
( 5, DR22, 'SJG123', ADD_MONTHS(TRUNC(SYSDATE),0)-130 )
( 6, DR22, 'GBC222', ADD_MONTHS(TRUNC(SYSDATE),0)-124 )
TRIPLEG TABLE
TRIPLEG( TripNo, LEGNo, DEPARTURE, DSTINATION )
CONSTRAINT TRIPLEG_PKEY PRIMARY KEY (TripNo, LEGNo),
CONSTRAINT TRIPLEG_UNIQUE UNIQUE(TripNo, DEPARTURE, DESTINATION),
CONSTRAINT TRIPLEG_FKEY1 FOREIGN KEY (TripNo) REFERENCES TRKTRIP(TripNo) );
INSERT INTO TRIPLEG VALUES( 1, 1, 'Armidale', 'Liverpool');
INSERT INTO TRIPLEG VALUES( 1, 2, 'Liverpool', 'Adelaide');
INSERT INTO TRIPLEG VALUES( 1, 3, 'Adelaide', 'Armidale');
INSERT INTO TRIPLEG VALUES( 3, 1, 'MayflowerSt', 'Auckland');
....
INSERT INTO TRIPLEG VALUES( 5, 1, 'CatmanSt', 'Chinatwon');
INSERT INTO TRIPLEG VALUES( 5, 2, 'Chinatwon', 'MayflowerSt');
我需要使用视图来实现。怎么做 ?我根本无法找回它。我应该使用左连接还是右连接
答案 0 :(得分:0)
这应该这样做:
select st.tripno,
st.departure as "START",
st.dstination as stop1,
stp1.dstination as stop2
from tripleg st
left join tripleg stp1
on stp1.tripno = st.tripno
and stp1.departure = st.dstination
where st.legno = 1
and st.tripno in (select tripno
from tripleg
group by tripno
having count(*) < 3);
这是一个SQLFiddle演示:http://sqlfiddle.com/#!4/7f773/1
如果您需要创建一个视图,只需运行:
create or replace view v_short_trips
as
select ...
有关如何创建基于视图的详细信息,请refer to the manual