Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign key to composite key

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 ?

like image 818
sn0ep Avatar asked Dec 20 '11 11:12

sn0ep


People also ask

Can foreign key point to composite key?

A referential constraint must have a one-to-one relationship between referencing and referenced columns. In other words, if the primary key is a set of columns (a composite key), then the foreign key also must be a set of columns that corresponds to the composite key.

Is composite key and foreign key same?

Composite key is a Candidate key that consists of more than one attribute. Foreign key is an attribute which is a Primary key in its parent table but is included as an attribute in the host table.

How do I create a composite foreign key in SQL?

You can create a composite foreign key just as you would create a single foreign key, except that instead of specifying just one column, you provide the name of two or more columns, separated by a comma.


2 Answers

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.

like image 61
marc_s Avatar answered Oct 27 '22 02:10

marc_s


alter table booking add constraint FK_Booking_TripAndDate
    foreign key (available_trip_code,date)
    references available_trip(trip_code, date)
like image 40
Andomar Avatar answered Oct 27 '22 00:10

Andomar