PDA

View Full Version : multi filed foreign key?


mothra
08-08-2004, 06:24 AM
I'm working on setting up some tables and I'm at a loss on how to relate tables when I need to use more than 1 field as a foreign key. Here's a quick example:

Given that there is a "Vendors" table and a "Stores" table. There can be a one to many relationship because each vendor can have one or more store locations. So what I want to do is make the primary key of the Vendors table = "vendor_name" and the foreign keys in the "Stores" table = "vendor_name" AND "location" (which is just an integer, not unique in the table).

I can't figure out how to set this up in the table!?

mothra
08-08-2004, 06:54 AM
nevermind... got it figured out.

Kiwi
08-08-2004, 12:02 PM
The trick is to define the primary key seperately:
CREATE TABLE invoice_hdr (
invoice_number INTEGER(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT PRIMARY KEY,
customer_id INTEGER(4) UNSIGNED ZEROFILL NOT NULL,
FOREIGN KEY (customer_id)
REFERENCES customer(customer_id)
);
CREATE TABLE items (
item_id INTEGER(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT PRIMARY KEY,
item_desc VARCHAR(255) NOT NULL,
FOREIGN KEY (customer_id)
REFERENCES customer(customer_id)
);
CREATE TABLE invoice_ln (
invoice_number INTEGER(4) UNSIGNED ZEROFILL NOT NULL,
invoice_line_number INTEGER(2) UNSIGNED ZEROFILL NOT NULL,
item_id INTEGER(4) UNSIGNED ZEROFILL NOT NULL,
FOREIGN KEY (item_id)
REFERENCES items(item_id),
FOREIGN KEY (invoice_number)
REFERENCES invoice_hdr(invoice_number),
PRIMARY KEY (invoice_number, invoice_line_number)
);