Search code examples
sqlprimary-keyforeign-key-relationshiporacle12ccompound-key

Oracle SQL 12c How to correctly use compound foreign keys in compound primary keys?


DISCLAIMER: I am a student. I do not work for an airline. I do not pretend to be a professional programmer.

Greetings, I want understand what I need to correct in order for these tables to work together. I'm sure it is obvious, but it isn't to me. To me, it looks like I'm matching my columns correctly. I'm sure it has to do with using a compound foreign key as part of my compound primary key - but I don't know how to correct this. My full code, with many 'TODOs' still remaining, is on Github Gist here.

I do not have access to an Oracle DBMS at this time, and won't for several days, so I'm using SQLFiddle; which doesn't give the full output SQLPlus or Developer could. It is also not optimal because I'm studying 12c, but SQLFiddle only offers 11g support. Thank you ahead of time.

This is SQL fiddle's error output:

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

And here are the two tables which don't agree with each other.

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)
);

Solution

  • I figured it out. I need a unique primary key, not made of foreign keys in the table - I don't have to display it later in my output, but I need to to select unique rows. Updated as below, it works just fine.

    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)
    );