數據完整性
數據完整性包括
-
實體完整性
- 主鍵約束
- 唯一約束
- 標識列
-
域完整性
- 數據類型約束
- 非空約束
- 默認值約束
-
引用完整性
- 外鍵約束
-
自定義完整性
- 存儲過程
- 觸發器
主表和從表
- 主表與從表的關系
- 主表中沒有的記錄,從表不允許插入
- 從表中有的記錄,主表中不允許刪除
-
- 刪除主表前,先刪從表
外鍵
- 外鍵
- 從表中的公共字段
- 只有innodb才能支持外鍵
- 公共字段的名字可以不一樣,但是數據類型要一樣
- 通過關鍵字foreign key配置
創建表的時候添加外鍵
-- 創建主表
drop table if exists stuinfo;
create table stuinfo(
id tinyint primary key,
name varchar(20)
)engine=innodb;
-- 創建從表,添加外鍵
drop table if exists stuscore;
create table stuscore(
sid tinyint primary key,
score tinyint unsigned,
foreign key(sid) references stuinfo(id)
)engine=innodb;
通過修改表的時候添加外鍵
- 語法
alter table 從表 add foreign key(公共字段) references 主表(公共字段)
drop table if exists stuinfo;
create table stuinfo(
id tinyint primary key,
name varchar(20)
)engine=innodb;
drop table if exists stuscore;
create table stuscore(
sid tinyint primary key,
score tinyint unsigned
)engine=innodb;
alter table stuscore add foreign key (sid) references stuinfo(id)
刪除外鍵
- 通過外鍵的名字刪除外鍵
-- 刪除外鍵
mysql> alter table stuscore drop foreign key `stuscore_ibfk_1`;
# `Query OK, 0 rows affected (0.00 sec)`
# `Records: 0 Duplicates: 0 Warnings: 0`
三種外鍵操作
-
嚴格限制
- 參見主表和從表
-
置空操作(set null)
- 如果主表記錄刪除,或關聯字段更新,則從表外鍵字段被設置為null
-
級聯操作(cascade)
- 如果主表記錄刪除,則從表記錄也被刪除
- 主表更新,從表外鍵字段也更新
-
語法
foreign key (外鍵字段) references 主表名 (關聯字段) [主表記錄刪除時的動作] [主表記錄更新時的動作]
-
小結
- 一般說刪除時置空,更新時級聯
- 置空、級聯操作中外鍵不能是從表的主鍵
-- 創建主表
drop table if exists stuinfo;
create table stuinfo(
id tinyint primary key comment '學號,主鍵',
name varchar(20) comment '姓名'
)engine=innodb;
-- 創建從表,刪除時置空,更新時級聯
drop table if exists stuscore;
create table stuscore(
id int auto_increment primary key comment '主鍵',
sid tinyint comment '學號,外鍵',
score tinyint unsigned comment '成績',
foreign key(sid) references stuinfo(id) on delete set null on update cascade
)engine=innodb;