[英]Can a table in SQL have multiple columns as foreign keys that refer only to one primary key of another table?
For instance, table Companies has columns company_name, first_contact, second_contact and table contacts have columns id(PK), name, phone. 例如,表Companies的列有company_name,first_contact,second_contact,表联系人的列有id(PK),名称,电话。 Can a table (companies) in SQL have multiple columns as foreign keys that refer only to one primary key of another table (contacts)? SQL中的表(公司)是否可以有多列作为外键,它们仅引用另一张表(联系人)的一个主键?
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. 您可以通过在设计中将first_contact声明为NOT NULL
来做到这一点,但是没有SQL约束要求每个公司的第三张表中都存在一行。 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) 查询数据时,您必须多次加入Contacts表(每列一次为外键)
select *
from Companies c
join Contacts contact1 on c.first_contact=contact1.id
join Contacts contact2 on c.second_contact=contact2.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.