Reputation: 131
For instance, table Companies has columns company_name, first_contact, second_contact and table contacts have columns id(PK), name, phone. Can a table (companies) in SQL have multiple columns as foreign keys that refer only to one primary key of another table (contacts)?
Upvotes: 1
Views: 1064
Reputation: 562250
Yes, here's an example:
mysql> CREATE TABLE Contacts (id INT PRIMARY KEY);
Query OK, 0 rows affected (0.03 sec)
mysql> CREATE TABLE Companies (id INT PRIMARY KEY, company_name TEXT,
-> first_contact INT, second_contact INT,
-> FOREIGN KEY (first_contact) REFERENCES Contacts(id),
-> FOREIGN KEY (second_contact) REFERENCES Contacts(id)
-> );
Query OK, 0 rows affected (0.03 sec)
But it would be more common to design the database another way, with a third table instead of the two foreign keys in Companies:
mysql> CREATE TABLE CompanyContacts (
-> contact_id INT NOT NULL,
-> company_id INT NOT NULL,
-> is_primary BOOL NOT NULL,
-> PRIMARY KEY (contact_id, company_id),
-> FOREIGN KEY (contact_id) REFERENCES Contacts(id),
-> FOREIGN KEY (company_id) REFERENCES Companies(id)
-> );
Query OK, 0 rows affected (0.04 sec)
Some advantages:
Some disadvantages:
NOT NULL
in your design, but there's no SQL constraint that requires a row to exist in the third table for each company.Upvotes: 2
Reputation: 347
Sure! You'd essentially have several one-to-one relationships from Companies to Contacts.
When querying the data, you'd have to join in the Contacts table multiple times (once per column that is a foreign key)
select *
from Companies c
join Contacts contact1 on c.first_contact=contact1.id
join Contacts contact2 on c.second_contact=contact2.id
Upvotes: 0