我想创建一个存储过程,让我知道以西班牙为目的地的航班的预计时间(新机场在西班牙)。我有以下表格:
FLIGHT_PLAN(plan_number NUMBER, outgoing_airport NUMBER, estimated_flight_time NUMBER, incoming_airport NUMBER);
AIRPORT (code NUMBER, name VARCHAR(20), city_code NUMBER);
CITY (code NUMBER,name VARCHAR(20),country_code NUMBER);
COUNTRY (code NUMBER, name VARCHAR(20));
我怎么能经历这个?如何将incomming_airport
中的FLIGHT_PLAN
字段与AIRPORT
中的代码链接起来,然后在CITY
中编码并在COUNTRY
中编码?
我应该使用外键还是什么?
答案 0 :(得分:0)
您可以使用
链接表格FROM COUNTRY C
inner join CITY I on I.country_code = C.code
inner join AIRPORT A on A.city_code = I.code
inner join FLIGHT_PLAN F on F.incoming_airport = A.code
WHERE C.name = 'Spain'
注意:Oracle非常敏感,所以请注意西班牙语的拼写,或使用
WHERE UPPER(C.name) = 'SPAIN'
答案 1 :(得分:0)
SELECT plan_number, outgoing_airport, incoming_airport, estimated_flight_time FROM flight_plan WHERE incoming_airport IN (SELECT ap.code FROM airport ap JOIN city ct ON ct.code = ap.city_code JOIN country co ON co.code = ct.country_code WHERE co.name = 'Spain')
如果您知道西班牙的代码,可以在子选择中省略JOIN并直接添加WHERE ct.country_code = 42
如果您在结果中需要机场的名称和城市,则必须再次加入机场和城市的主要查询:
SELECT fp.plan_number, fp.estimated_flight_time, fp.outgoing_airport, out_ap.name as outgoing_airport_name, out_city.name as outgoing_city_name, fp.incoming_airport, in_ap.name as incoming_airport_name, in_city.name as incoming_city_name FROM flight_plan fp JOIN airport in_ap ON in_ap.code = fp.incoming_airport JOIN city in_city ON in_city.code = in_ap.city_code JOIN airport out_ap ON out_ap.code = fp.outgoing_airport JOIN city out_city ON out_city.code = out_ap.city_code WHERE incoming_airport IN (SELECT ap.code FROM airport ap JOIN city ct ON ct.code = ap.city_code JOIN country co ON co.code = ct.country_code WHERE co.name = 'Spain')