完整性限制
not null
添加值時該列不可為空
default
預設值,當添加值時未給設定預設值列添加值時,該列使用預設的值
unique
唯一限制,指定列的值不可重複
primary key
主鍵限制,不為空且唯一
auto_increment
設定自增列,每次添加資料時,自增列可以不寫值,會自動設定值
通過
auto_increment=數字
設定起始值
create table 表名(列名 資料類型 primary key auto_increment);
create table 表名(列名 資料類型 primary key auto_increment)auto_increment=5;# 設定起始值
foreign key
外鍵限制
表與表之間的關系:
- 一對一
- 多對一
- 多對多
建立外鍵關系
方式一:建立表後添加關系
create table sex
(seid int not null,primary key (seid));
create table stu(id int not null,sex int,primary key (id));
alter table stu add constraint FK_Reference_1 foreign key (sex)
references sex (seid)
on delete restrict on update restrict
方式二:建立表時添加關系
create table sex(sexid int primary key,name varchar(55));
create table stu(stuid int primary key,sex int,
constraint fk1 foreign key(sex) references sex(sexid));
create table stu(stuid int primary key,sex int,
constraint 外鍵名 foreign key(目前表外鍵) references 外鍵表(外鍵表主鍵));
删除外鍵關系
alter table 表名 drop foreign key 外鍵名
級聯
級聯有三種模式:嚴格模式、cascade、set null
嚴格模式
有外鍵限制時,被關聯字段不能随意删除和修改(預設)
cascade
有外鍵限制時,被關聯字段被修改時,關聯字段會随着修改
ser null
有外鍵限制時,被關聯字段被修改時,關聯字段會為空
設定級聯
constraint fk_t1_publish foreign key(pid) references publish(id)
on delete cascade on update cascade; # 設定級聯
alter table stu add constraint FK_Reference_1 foreign key (sex)
references sex (seid)
on delete restrict on update restrict; # 設定級聯