Mysql 常见约束
2020.03.11 12:35
2020.03.11 12:44
1. 常见约束
含义:一种限制,用于限制表中的数据,为了保证表中的数据的准确性和可靠性;
分类:六大约束
- not null 非空约束,用于保证字段的值不能为空
- default 默认,用于保证该字段有默认值
- primary key 主键,用于保证该字段具有唯一性,且非空
- unique 唯一约束,用于保证该字段具有唯一性,可以为空
- check 检查约束(mysql不支持,SQLserver等支持)用于插入数据时,检查插入数据是否满足check约束(满足才允许插入)
- foreign key 外键,限制两个表的关系,用于保证该字段的值,必须来自主表的关联列的值;在从表中添加外键约束,用于引用主表中某列的值;
添加约束的时机:
- 创建表时
- 修改表时
但是都在数据添加之前,否则极有可能有问题!
约束的添加分类:
- 列级约束,在创建列时,在该列的后面直接添加约束
- 六大约束语法上都支持,但外键约束没有效果;
- 表级约束,在所有列的后面,单独添加约束;
- 除了非空和默认,其他都支持;
列级约束:
create table major
(
id int primary key,
majorName varchar(20)
);
create table stuInfo
(
id int primary key, # 主键约束
stuName varchar(20) not null,# 非空
gender char(1) check ( gender = '男' or gender = '女' ),#检查约束,mysql中无效,但不报错
seat int unique, #唯一约束
age int default 18,#默认
majorId int references major (id) #外键约束,但是这里并未生效,需要使用下面的语句
# constraint fk_major_id foreign key (majorId) references major (id)
);
表级约束:
create table stuInfo
(
id int,
stuName varchar(20),
gender char(1),
seat int unique,
age int default 18,
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 if not exists stuinfo
(
id int primary key,
stuname varchar(20) not null,
sex char(1),
age int default 18,
seat int unique,
majorid int,
constraint fk_stuinfo_major foreign key (majorid) references major (id)
);
修改表时添加约束:
1、如,添加可空约束:
alter table stuInfo
modify column stuname varchar(20) null;
2、也如,添加默认约束:
alter table stuInfo
modify age int default 20;
3、添加唯一约束
alter table stuInfo
add unique (seat);
4、添加外键
alter table stuInfo
add constraint fk_stuinfo_major foreign key (majorid) references major (id);
其中,constraint fk_stuinfo_major
可以省略!
5、删除非空
alter table stuinfo
modify column stuName varchar(20) null;
也即:modify
后面跟的是某列的完全约束(覆盖其他的);
6、删除主键
alter table stuInfo
drop primary key;
7、删除唯一
alter table stuInfo drop index seat;
8、删除外键
alter table stuInfo drop foreign key majorid
2. 自增列
很简单的一个概念,也即为某个列添加自增的特性;
这常用在主键id上,使用关键词auto_increment
,所以一般创建表都是:
create table tab_identify
(
id int primary key auto_increment
);
这样,就可以使用主键id自动递增,且插入数据时不用插入id;
本节阅读完毕!
(分享)