Foreign key to composite key

喜夏-厌秋 提交于 2019-11-30 03:33:18

问题


I have a problem i need to reference a single foreign key to a composite key in another table.

My database structure is as following:

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

my question is: how do I let booking.available_trip_code reference to available_trip.trip_code and available_trip.date ?


回答1:


If you reference a composite primary key, your foreign key also needs to contain all those columns - so you need something like:

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

If you don't already have all those columns present in your table, then you'll need to add them.




回答2:


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


来源:https://stackoverflow.com/questions/8575046/foreign-key-to-composite-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!