约束
什么是约束 (constraint)
约束就是一种限制,
数据库的约束,是对数据的安全性,完整性的保证;
mysql中的约束
unique (唯一)
唯一性约束,表示这个字段不能出现重复的值,用于唯一标识一条记录
主要用于:身份证,学号等
not null (非空)
非空约束,表示这个字段的值不能为空
主要用于: 账户名/密码
null
一些数据类型默认就是可以为空
default
默认值,用于给某一字段设置默认值
普通约束例子:
# 完整的建表语句 create table 表名(字段名 字段类型[(宽度)约束]) charset utf8; # 学生类(类型具备:学号/姓名/性别) create table student( id int unique, name char(10) not null, gender enum("women","man") default "man" ); insert into student values(null,null,null); # 因为name约束了不能为空,所以会报错 ERROR 1048 (23000): Column 'name' cannot be null insert into student values(null,"jack",null); # 给name加入值,就可以了,但是我们的学号和性别都是null,这 # 样不行,虽然性别设置了默认值,但因为传入了null,系统默认 有值 Query OK, 1 row affected (0.38 sec) +------+------+--------+ | id | name | gender | +------+------+--------+ | NULL | jack | NULL | +------+------+--------+ 1 row in set (0.00 sec) alter table student modify id int unique not null; # 如果要确保学号和性别都不能为空,那我们也要加非空,非常麻烦,所以出现了一个即表示,唯一性又是非空的约束条件,primary key
primary key
概述:
主键约束,从约束角度来看等于:非空+唯一
主键的作用:
在innodb存储引擎中,主键用于组织数据(树形结构),也就是说主键对于innodb引擎来说是必须要的,没有不行.
如果没有手动指定主键,mysql 会自动查找一个具备非空且唯一的字段为主键;
如果也没有这样的字段,mysql 会创建一个隐藏手段,作为主键;
主键是一种索引,unique也是,索引的作用就是加速查询
主键:具备约束的作用,还能加快我们的查询速度
如果本来的业务中存在非空且唯一的字段,那就把设为主键,如果没有就自己添加一个字段专门作为主键;
通常我们会将主键设置为 int 类型,为了方便保证其唯一性.
# auto_increment 表示主键自动增长字段,可以给null,会自动生成值 # 自动增长可以用在 具备索引,并且是数字类型的字段上,但是通常与主键一起使用! create table student1(id int primary key auto_increment, name char(10) not null); insert into student1 values (null,"jack"); Query OK, 1 row affected (0.39 sec) mysql> select * from student1; +----+------+ | id | name | +----+------+ | 1 | jack | +----+------+ 1 row in set (0.00 sec)
主键与普通的约束的区别
create table person( id char(19) primary key, name char(20) ); insert into person values("1","rose");# ok insert into person values("1","jack");# ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'主键冲突; insert into person values("2","jack"); # ok #从约束角度来看就等同于,非空+唯一 create table person2( id char(19) unique not noll, name char(20)