一. 简介
检察约束属于DDL
约束可以理解成一种校验方式
一共有5种约束,现在分别讲解一下
- 主键约束(Primary Key)不允许为空
不允许有重复值出现
保证数据的唯一性
- 外键约束(Foreign Key)允许有空值
允许有重复
值必须是参照表的参照列中所包含的值
保证数据的参照完整性
- 唯一性约束(Unique)相同值只能出现一次
允许为多个列添加唯一性约束
保证数据的唯一性
- 非空约束(Not Null)列中不能有空值
允许重复值
允许为多个列添加非空约束
保证数据没有空值
- 检查约束(Check)用户自己定义约束条件
保证数据满足自定义的条件约束
MySQL 目前不支持检查约束
二. 主键约束(primary key)
1. 添加主键约束
alter table 表名 add primary key(列名)
例
显然这里的id字段(列)要设置成主键- alter table students add primary key(id);
复制代码 因为是主键,那么在当前表中是唯一的
如果主键是 int 型,那么就可以使用自动增长
alter table 表名 modify 主键 类型 auto_increment- alter table student modify id int auto_increment
复制代码
2. 删除主键
alter table 表名 drop primary key- alter table students drop primary key;
复制代码 三. 外键约束(Foreign Key)
1. 添加外键
alter table 表名 add constraint 约束名 foreign key(列名) references 参照的表名(参照的列名)单词:
constraint : 约束
references:引用- alter table students
- add constraint fk_students_courses
- foreign key (course_id)
- references courses(id);
复制代码 2. 删除外键
alter table 表名 drop foreign key 约束名- alter table students
- drop foreign key fk_students_courses;
复制代码 四. 唯一性约束(Unique)
1. 添加唯一约束
alter table 表名 add constraint 约束名 unique(列名)- alter table students
- add constraint uk_students_name
- unique (name);
复制代码 2. 删除唯一约束
alter table 表名 drop key 约束名- alter table students
- drop key uk_students_name;
复制代码 五. 非空约束(Not Null)
1. 添加非空约束
alter table 表名 modify 列名 类型 not null单词:
modify:修改
在修改的时候添加非空约束- alter table students
- modify name varchar(50) not null;
复制代码 2. 删除非空约束
alter table modify 列名 类型 null- alter table students
- modify name varchar(50) null;
复制代码 六. 创建表时添加约束
直接可以在创建的时候顺便添加约束- create table enhanced_students (
- -- 添加主键约束,并自动增长
- id int auto_increment primary key,
- -- 添加非空约束(不能为空)
- name varchar(50) not null,
- gender enum('男', '女') not null,
- -- 添加唯一约束
- students_name varchar(30) unique
- );
复制代码 七. 总结
到此这篇关于MySQL中检查约束的文章就介绍到这了,更多相关MySQL检查约束内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
来源:https://www.jb51.net/database/338567z76.htm
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |