![](/img/trans.png)
[英]Composite Primary Key's columns each refer to a Primary Key of another table. What should be the Foreign Keys for this table?
[英]Can a table in SQL have multiple columns as foreign keys that refer only to one primary key of another table?
例如,表Companies的列有company_name,first_contact,second_contact,表聯系人的列有id(PK),名稱,電話。 SQL中的表(公司)是否可以有多列作為外鍵,它們僅引用另一張表(聯系人)的一個主鍵?
是的,這里有一個例子:
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)
但是用另一種方法設計數據庫會更常見,用第三張表而不是公司中的兩個外鍵:
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)
一些優點:
一些缺點:
NOT NULL
來做到這一點,但是沒有SQL約束要求每個公司的第三張表中都存在一行。 當然! 從公司到聯系人,您實際上具有幾種一對一的關系。
查詢數據時,您必須多次加入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.