约束分类
NOT NULL
DEFAULT
PRIMARY KEY
UNIQUE
唯一,用于保证该字段的值是唯一的,但是可以为空(有点像unique key)
check
foregin key
外键约束,为了限制两个表之间的关系
# 添加列级约束create table stuinfo(id INT primary key,# 主键stuName varchar(20) not null,# 非空gender char(1) check(gender='男' or gender ='女'),# 检查seat int unique,# 唯一age int default 18,# 默认marjorId int references major(id) # 外键);create table major(id int primary key,majorName varchar(20));desc stuinfo;show index from stuinfo;# 查看stuinfo中的索引CREATE TABLE `stuinfo` (`id` int(11) NOT NULL,`stuName` varchar(20) COLLATE utf8_bin NOT NULL,`gender` char(1) COLLATE utf8_bin DEFAULT NULL,`seat` int(11) DEFAULT NULL,`age` int(11) DEFAULT '18',`marjorId` int(11) DEFAULT NULL,PRIMARY KEY (`id`),UNIQUE KEY `seat` (`seat`),CONSTRAINT `stuinfo_chk_1` CHECK (((`gender` = _utf8mb4'男') or (`gender` = _utf8mb4'女')))) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;# 添加表级约束drop table if exists stuinfo;create table stuinfo(id int,stuname varchar(20),gender char(1),seat int,majorid int,CONSTRAINT pk PRIMARY key(id),# 主键CONSTRAINT uq UNIQUE(seat),# 唯一CONSTRAINT CK check(gender = '男' or gender = '女'),CONSTRAINT fk_stuinfo_major FOREIGN KEY (majorid) references major(id)#外键);CREATE TABLE `stuinfo` (`id` int(11) NOT NULL,`stuname` varchar(20) COLLATE utf8_bin DEFAULT NULL,`gender` char(1) COLLATE utf8_bin DEFAULT NULL,`seat` int(11) DEFAULT NULL,`majorid` int(11) DEFAULT NULL,PRIMARY KEY (`id`),UNIQUE KEY `uq` (`seat`),KEY `fk_stuinfo_major` (`majorid`),CONSTRAINT `fk_stuinfo_major` FOREIGN KEY (`majorid`) REFERENCES `major` (`id`),CONSTRAINT `CK` CHECK (((`gender` = _utf8mb4'男') or (`gender` = _utf8mb4'女')))) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
主键和唯一的区别
主键和唯一都可以保证为唯一性
主键不能为空,但唯一可以为空
主键表中只能有一个,唯一可以有多个
主键可以组合(多个字段组合在一起)唯一也支持组合()
需要注意的是在唯一中,null是互相不相等的。
外键关联的是主键或者唯一
修改表时,添加约束
## 添加非空
alter table tableName modify column column_name 类型 not null;
### 添加默认约束
alter table tableName modify column column_name 类型 default 10;
## 添加主键
#### 列级添加
alter table stuinfo column id int(11) primary key;
# 或者表级添加
alter table stuinfo add primary key(id);
## 添加唯一
alter table stuinfo modify column seat int unique;
alter table stuinfo add unique(seat);
alter table stuinfo add unique index(seat);
### 添加外键
alter table stuinfo add constraint fk_stuinfo_major foreign key(majorid) references major(id);
修改表时,删除约束
## 添加非空
alter table tableName modify column column_name 类型 null;
### 添加默认约束
alter table tableName modify column column_name 类型;
## 添加主键
#### 列级添加
alter table stuinfo column id int(11);
# 或者表级添加
alter table stuinfo drop primary key;
## 添加唯一
alter table stuinfo modify column seat int;
alter table stuinfo drop index seat;
### 添加外键
alter table stuinfo drop foreign key fk_stuinfo_major;
查看表中的索引
show index from table_name;
