Jump to content

USE OF DUPLICATE FOREIGN KEYS WHEN CREATING A TABLE


Recommended Posts

Hi.. Im a bit stuck on creating a table that references the same foreign key that exists in two different tables.

 

Here's my table layout so far..

 

Student - (student_id, name)

 

Book - (book_id, student_id)

 

Sales - (sale_id, student_id(the seller), student_id(the buyer))

 

Basically.. the student_id in the book table is the 'seller' of the book. When the user logs into the page.. he is the 'buyer' in a sense.. so when that user buys a book.. his ID gets posted into the sales table, whilst the sellers id also gets posted into the SALE table. Both the seller and buyer's ID comes from the Student_id field.

 

Obviously I cant have a duplicate foreign key in the sales table.. so is there any way round this???

You can't have a duplicate foreign key, correct. But what you are missing is that the Sales table doesn't need to have the fields named exactly as its helper tables.

 

Sales - (sale_id, seller, buyer)

 

Makes sure seller and buyer are of the same type as student_id and then create the foreign key relationship for each of them

 

ALTER TABLE Sales
  ADD CONSTRAINT sales_fk_seller
  FOREIGN KEY (seller)
    REFERENCES Student (student_id)
    ON DELETE RESTRICT
    ON UPDATE RESTRICT; /* check your specific rules */

ALTER TABLE Sales
  ADD CONSTRAINT sales_fk_buyer
  FOREIGN KEY (buyer)
    REFERENCES Student (student_id)
    ON DELETE RESTRICT
    ON UPDATE RESTRICT; /* check your specific rules */

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.