简体   繁体   English

外键引用

[英]Foreign Key Reference

I addressed in class that the 2 foreign keys in the FlightData table are Depart_Code and Ariv_Code that there isn't any table to make references to them being a primary key in, in the relational schema we were given.我在 class 中提到FlightData表中的 2 个外键是Depart_CodeAriv_Code ,在我们给出的关系模式中,没有任何表可以引用它们作为主键。

In class I was told that they reference Airport_Code in the Airport table.Airport_Code中,有人告诉我他们在Airport表中引用了 Airport_Code。 I was wondering I would go about doing that?我想知道我会 go 这样做吗? I feel like I am missing something obvious.我觉得我错过了一些明显的东西。 I appreciate any help offered I am still new to database in general and I am currently on Oracle 11g.我很感激提供的任何帮助我对数据库还是新手,我目前在 Oracle 11g 上。

Airport table机场

CREATE TABLE Airport
(
     Airport_Code VARCHAR2(7) CONSTRAINT pk_Airport Primary Key,
     City_Code VARCHAR2(3), 
     CONSTRAINT fk_Airport_City_Code 
         FOREIGN KEY(City_Code) REFERENCES City, 
     Airport_Name VARCHAR2(30)
);

FlightData table:飞行数据表:

CREATE TABLE FlightData
(
    Flt_Nbr VARCHAR2(3) CONSTRAINT pk_FlightData Primary Key,
    Depart_Code VARCHAR2(30), 
    Ariv_Code VARCHAR2(30)
);

To make sure Depart_Code and Ariv_Code always reference an airport in the Airport table you need to:要确保Depart_CodeAriv_Code始终引用Airport表中的机场,您需要:

  • Make these columns NOT NULL .使这些列NOT NULL
  • Ensure they have the same data type as the key in Airport .确保它们与Airport中的键具有相同的数据类型。 Make them have a length of 7 .使它们的长度为7
  • Add two foreign key constraints, each one based on each column.添加两个外键约束,每一个都基于每一列。

For example, the second table could look like:例如,第二个表可能如下所示:

CREATE TABLE FlightData (
  Flt_Nbr VARCHAR2(3) CONSTRAINT pk_FlightData Primary Key,
  Depart_Code VARCHAR2(7) not null,
  constraint fk1 foreign key (Depart_Code) references Airport (Airport_Code),
  Ariv_Code VARCHAR2(7) not null,
  constraint fk2 foreign key (Ariv_Code) references Airport (Airport_Code)
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM