2011-12-20 15 views
5

Mam problem, muszę odnieść się do jednego klucza obcego do klucza złożonego w innej tabeli.Klucz obcy do klucza złożonego

My struktury bazy danych jest następujący:

CREATE TABLE available_trip (
trip_code integer not null, 
date datetime not null, 
primary key(trip_code, date), 
FOREIGN KEY (trip_code) REFERENCES trip (trip_code) 
); 

CREATE TABLE booking (
    available_trip_code integer not null, 
    customer_code integer not null, 
    date datetime not null, 
    deposit float not null, 
    total_price float not null, 
    has_paid float not null, 
    description_en nvarchar(12) null, 
    finance_type_code nvarchar(12) not null, 
    primary key(available_trip_code, customer_code, date), 
    FOREIGN KEY (available_trip_code) REFERENCES available_trip (trip_code, date), 


FOREIGN KEY (customer_code) REFERENCES customer (customer_code), 
      FOREIGN KEY (finance_type_code) REFERENCES finance_type (finance_type_code) 
     ); 

moje pytanie brzmi: w jaki sposób mogę pozwolić booking.available_trip_code odniesienie do available_trip.trip_code i available_trip.date?

Odpowiedz

9

Jeśli odwołać kompozytowy klucz podstawowy, klucz obcy musi również zawierać wszystkie te kolumny - więc trzeba coś takiego:

FOREIGN KEY (available_trip_code, date) 
      REFERENCES available_trip (trip_code, date) 

Jeżeli nie masz jeszcze wszystkie te kolumny znajdujące się w tabeli , musisz je dodać.

4
alter table booking add constraint FK_Booking_TripAndDate 
    foreign key (available_trip_code,date) 
    references available_trip(trip_code, date)