Oracle SQL 12c如何在复合主键中正确使用复合外键?

时间:2016-05-07 00:20:40

标签: sql primary-key foreign-key-relationship oracle12c compound-key

免责声明:我是学生。我不为航空公司工作。我不假装成为一名专业程序员。

问候,我想了解我需要纠正的内容,以便这些表一起工作。我确定这很明显,但对我来说并非如此。对我来说,看起来我正确地匹配了我的列。我确定它与使用复合外键作为复合主键的一部分有关 - 但我不知道如何纠正这个问题。我的完整代码,包含许多' TODO'仍然存在,是在Github Gist here

我目前无法访问Oracle DBMS,并且已经好几天了,所以我使用的是SQLFiddle;哪个没有给出完整输出SQLPlus或Developer可以。它也不是最佳的,因为我学习12c,但SQLFiddle只提供11g支持。提前谢谢你。

这是SQL小提琴的错误输出:

ORA-02256: number of referencing columns must match referenced columns

以下两张表并不相同。

CREATE TABLE FLIGHT (
  FLIGHT_ID NUMBER(3),
  AIRCRAFT_ID VARCHAR(8),
  FLIGHT_DATE DATE,
  CONSTRAINT PK_flight_comp_pk PRIMARY KEY (FLIGHT_ID,FLIGHT_DATE),
  CONSTRAINT FK_flight_route_ID FOREIGN KEY (FLIGHT_ID)
    REFERENCES FLIGHT_ROUTE(ROUTE_ID),
  CONSTRAINT FK_flight_serial_ID FOREIGN KEY (AIRCRAFT_ID)
    REFERENCES AIRCRAFT(AIRCRAFT_ID)
);

CREATE TABLE RESERVATIONS (
  CUSTOMER_ID NUMBER(4),
  FLIGHT_ID NUMBER(3),
  QTY_RESERVED_SEATS NUMBER(3),
  CONSTRAINT PK_reservations PRIMARY KEY (CUSTOMER_ID,FLIGHT_ID),
  CONSTRAINT FK_reservations_customer_ID FOREIGN KEY (CUSTOMER_ID)
    REFERENCES CUSTOMER(CUSTOMER_ID),
  CONSTRAINT FK_reservations_flight_ID FOREIGN KEY (FLIGHT_ID)
    REFERENCES FLIGHT(FLIGHT_ID,FLIGHT_DATE)
);

1 个答案:

答案 0 :(得分:0)

我明白了。我需要一个唯一的主键,而不是表中的外键 - 我不必在输出中稍后显示它,但我需要选择唯一的行。更新如下,它工作得很好。

CREATE TABLE FLIGHT (
  FLIGHT_ID NUMBER(5),
  ROUTE_ID NUMBER (3),
  AIRCRAFT_ID VARCHAR(8),
  FLIGHT_DATE DATE,
  CONSTRAINT PK_flight_comp_pk PRIMARY KEY (FLIGHT_ID),
  CONSTRAINT FK_flight_route_ID FOREIGN KEY (ROUTE_ID)
    REFERENCES FLIGHT_ROUTE(ROUTE_ID),
  CONSTRAINT FK_flight_serial_ID FOREIGN KEY (AIRCRAFT_ID)
    REFERENCES AIRCRAFT(AIRCRAFT_ID)
);

CREATE TABLE RESERVATIONS (
  RESERVATIONS_ID NUMBER (6),
  CUSTOMER_ID NUMBER(4),
  FLIGHT_ID NUMBER(5),
  QTY_RESERVED_SEATS NUMBER(3),
  CONSTRAINT PK_reservations PRIMARY KEY (RESERVATIONS_ID),
  CONSTRAINT FK_reservations_customer_ID FOREIGN KEY (CUSTOMER_ID)
    REFERENCES CUSTOMER(CUSTOMER_ID),
  CONSTRAINT FK_reservations_flight_ID FOREIGN KEY (FLIGHT_ID)
    REFERENCES FLIGHT(FLIGHT_ID)
);