一种限制,用于限制表中的数据,为了保证表中的数据的准确和可靠性。
列级约束通常直接写在字段类型后面,如下:
create table 表名(
字段名 字段类型 列级约束,
字段名 字段类型 列级约束,
);
# 学生表
create table student(
id int primary key, # 主键
stuName varchar(20) not null, # 非空
gender char(1) check(gender='男' or gender='女'), # 检查
seat int unique, # 唯一约束
age int default 18, # 默认约束
majorId int foreign key references major(id) # 外键约束
)
# 课程表
create table major(
id int primary key,
majorName varchar(20)
);
注意:六大约束在语法上都支持,不会报错,但外键约束和检查约束没有效果
表级约束通常在所有字段的最下面,语法如下:
create table 表名(
字段名 字段类型,
字段名 字段类型,
# 表级约束
【constraint 别名】 约束类型(字段名),
...
);
# 学生表
create table student(
id int,
stuName varchar(20),
gender char(1),
seat int,
age int,
majorId int,
# 添加表级约束
constraint pk primary key(id), # 给id添加主键约束
constraint uq unique(seat),
constraint ck check(gender='男' or gender='女'), #检查约束
constraint fk_student_major foreign key(majorId) references major(id) # 外键约束
)
# 课程表
create table major(
id int primary key,
majorName varchar(20)
);
表级约束中,不支持非空和默认约束
对比主键与唯一键
(1)主键和唯一键都要保证唯一性
(2)主键不可以为空,唯一键可以为空
(3)一个表中至多一个主键,但可以有多个唯一键
语法:
# 列级约束
alter table 表名 modify column 列名 类型 约束类型
# 表记约束
alter table 表名 add 【constraint 约束名】 约束类型(字段名) 【外键的引用】
例如:
# 添加非空约束
alter table student modify column stuName varchar(20) not null;
# 添加默认约束
alter table student modify column age int default 18;
# 添加主键
# (1) 列级约束
alter table student modify column id int primary key;
# (2) 表级约束
alter table student add primary key(id);
# 添加唯一键
# (1) 列级约束
alter table student modify column seat int unique;
# (2) 表级约束
alter table student add unique(seat);
# 添加外键
alter table student add foreign key(majorid) references major(id);
列级约束不支持起别名,表级约束可以起别名
# 删除非空约束
alter table student modify column stuName varchar(20) null;
# 删除主键
alter table student drop primary key;
# 删除默认约束
alter table student modify column age int;
# 删除唯一
alter table student drop index seat;
# 删除外键
alter table student drop foreign key majorid;
又称为自增长列,可以不用手动的插入值,系统提供默认的序列值
create table tab_identity(
id int primary key auto_increment,
name varchar(20)
);
# 插入数据
insert into tab_identity values(null,'john');
insert into tab_identity values(null,'john');
insert into tab_identity values(null,'john');
insert into tab_identity values(null,'john');
select * from tab_identity;

通过下面的语句可以查看标识列的步长和起始值
show variables like '%auto_increment%';

通过下面的语句可以修改标识列的步长,mysql中不支持修改起始值。
set auto_increment_increment=3;
特点
(1)标识列需要和一个键搭配(主键,唯一键等)
(2)一个表至多一个标识列
(3)标识列的类型只能是数值型
alter table tab_identity modify column id int primary key auto_increment;
alter table tab_identity modify column id int ;