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.
)[/code]
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
Example:
The "Persons" table:
The "Orders" table:
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,否则这一条目不成立.
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_Id | LastName | FirstName | Address | City |
---|---|---|---|---|
1 | Hansen | Ola | Timoteivn 10 | Sandnes |
2 | Svendson | Tove | Borgvn 23 | Sandnes |
3 | Pettersen | Kari | Storgt 20 | Stavanger |
O_Id | OrderNo | P_Id |
---|---|---|
1 | 77895 | 3 |
2 | 44678 | 3 |
3 | 22456 | 2 |
4 | 24562 | 1 |
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,否则这一条目不成立.
相关文章推荐
- 升级Oracle 10..2.0.1到Oracle 10.2.0.5
- join operations in SQL
- jfinal学习笔记二(连接数据库)
- 数据库联表查询
- window下安装php memcached扩展
- Redis首页
- Redis文档
- Redis社区
- Redis下载
- Redis支持
- ORM选型
- Java操作MongoDB
- Oracle第学习四天
- mysql 主从配置详解(windows<->ubuntu)
- Linux环境搭建nginx+2个tomcat+2个redis(主从复制)
- 转 全国高校信息数据库,全国高校排序数据库
- message from server: "Host 'XXXX' is not allowed to connect to this MySQL server"
- 【翻译自mos文章】Oracle GoldenGate 对IBM大型机 z/OS 2.1 和DB2 v11的支持
- 浅析postgresql数据库事务及行锁特征
- redis的主配置文件说明