您的位置:首页 > 数据库

SQL primary key, foreign key

2016-02-12 09:45 423 查看
PRIMARY KEY 是为了保证数据的完整性

FOREIGN KEY 是为了保证数据引用的完整性

The PRIMARY KEY constraint uniquely identifies each record in a database table.

CREATE TABLE Persons
(
Id_P int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
[code]PRIMARY KEY (Id_P)

)[/code]

A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

Example:
The "Persons" table:

P_IdLastNameFirstNameAddressCity
1HansenOlaTimoteivn 10Sandnes
2SvendsonToveBorgvn 23Sandnes
3PettersenKariStorgt 20Stavanger
The "Orders" table:
O_IdOrderNoP_Id
1778953
2446783
3224562
4245621
The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.

用法:

The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is created:

CREATE TABLE
Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
)

即要求foreign key必须是person中的primary key,否则这一条目不成立.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: