Search code examples
databaseforeign-key-relationshipdatabase-normalization

Normalization - Foreign key being repeated


When normalizing data is it acceptable to have a foreign key repeated in the same table?

e.g. A courier company has an orders form and a customers form, the order form would log what customer to pickup an item from (Customer_ID) and would also have a column for what customer it is being delivered to (also Customer_ID).


Solution

  • It is perfectly acceptable; the two indexes will be maintained separately. The two relationships can be used separately...

    select item, name, address from orders inner join customers on orders.sender = customers.id where orders.id = 5;
    select name, address from orders inner join customers on orders.recipient = customers.id where orders.id = 5;
    

    or together (with care)

    select item, name as sender_name, address as sender_address, recipients.name as as recipient_name, recipients.address as recipient_address from orders inner join customers on orders.sender = customers.id inner join customers as recipients on orders.recipient = recipients.id;
    

    Do be careful with cascade deletes ;)