FOREIGN KEY約束是用于兩個(gè)表連接在一起的關(guān)鍵。
FOREIGN KEY是一個(gè)表中的一個(gè)字段(或字段的集合),它引用另一個(gè)表中的PRIMARY KEY。
創(chuàng)建表"PersonID"時(shí),以下SQL在列上創(chuàng)建FOREIGN KEY "Orders":
MySQL:
CREATE TABLE Orders ( OrderID int NOT NULL, OrderNumber int NOT NULL, PersonID int, PRIMARY KEY (OrderID), FOREIGN KEY (PersonID) REFERENCES Persons(PersonID) );
SQL Server / Oracle / MS Access:
CREATE TABLE Orders ( OrderID int NOT NULL PRIMARY KEY, OrderNumber int NOT NULL, PersonID int FOREIGN KEY REFERENCES Persons(PersonID) );
若要命名FOREIGN KEY約束,并在多個(gè)列上定義FOREIGN KEY約束,請使用以下SQL語法:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Orders ( OrderID int NOT NULL, OrderNumber int NOT NULL, PersonID int, PRIMARY KEY (OrderID), CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID) REFERENCES Persons(PersonID) );
要在已經(jīng)創(chuàng)建表之后在"PersonID"列上創(chuàng)建FOREIGN KEY約束"Orders",請使用以下SQL:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
若要命名FOREIGN KEY約束,并在多個(gè)列上定義FOREIGN KEY約束,請使用以下SQL語法:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders ADD CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
要?jiǎng)h除FOREIGN KEY約束,請使用以下SQL:
MySQL:
ALTER TABLE Orders DROP FOREIGN KEY FK_PersonOrder;
SQL Server / Oracle / MS Access:
ALTER TABLE Orders DROP CONSTRAINT FK_PersonOrder;