目录
[五、primary key](#五、primary key)
为了保证数据的完整性和可预期性,表中一定要有各种约束,通过约束,让我们未来插入数据库表中的数据是符合预期的。
表的约束很多,这里主要介绍以下几个约束:null/not null,default,comment,zerofill,primary key,auto_increment,unique key。
一、NULL约束
数据库默认字段基本都是字段为空,但是实际开发时,尽可能保证字段不为空,因为数据为空无法参与运算。所以对于有些要求不能为空的数据,设置为not null,就保证了内容。

注意,空属性和语言中的NULL,不同,语言中的NULL可以参与运算,值为0,而mysql中的空是不能参与运算的。
当设置为not null时,是必须插入内容的。

二、default约束
默认值:某一种数据会经常性地出现某个具体的值,可以在一开始就指定好,在需要插入数据的时候,用户可以选择性地使用默认值。

默认值的生效:数据在插入的时候不给该字段赋值,就使用默认值。

注:
如果既设置了not null ,又设置了default默认值,它们会冲突吗?-----不会。

以上述为例:
如果设置了not null,而没有设置default,当不指定插入时会报错:

如果既设置了not null,又 设置了default,当没有指定插入时会默认选用default值插入:

如果既设置了not null,又设置了default,指定插入但是插入了null,会报错:

但是一般很少not null和default同时设置。
三、comment
列描述:comment,没有实际含义,专门用来描述字段,会根据表创建语句保存, 一般也叫做注释。

通过desc查看不到注释信息:

通过show可以看到:

四、zerofill
查看建表语句:

在建表时我们并没有设置int大小,那么括号中的10是什么意思?其实没有zerofill这个属性,括号内的数字是毫无意义的。

但是对列添加了zerofill属性后,显示的结果就有所不同了。修改t17表的属性:


可以看到a的值由原来的1变为了0000000001,这就是zerofill属性的作用。
如果宽度小于设定的宽度(这里设置的是10,可以自行调整),自动填充0.要注意的是,这只是最后显示的结果,在mysql中实际存储的还是1.
zerofill属性的作用在于格式化输出固定长度的数,比如在设置学号,教室号等可以采用这种方式。
五、primary key
主键: primary key 用来唯一地约束该字段里面的数据,不能重复,不能为空,一张表中最多只能有一个主键,主键所在的列通常是整数类型。
案例:
创建表的时候直接在字段上指定主键:

主键约束:主键对应的字段中不能重复,一旦重复,操作失败。

当表创建好以后但是没有主键的时候,可以再次追加主键。
alter table table_name add primary key(line_name)
删除主键。
alter table table_namedrop primary key;

复合主键
在创建表的时候,在所有字段之后,使用primary key(主键字段列表)来创建主键,如果有多个字段作为主键,可以使用复合主键。

根据插入的values删除某一行:
delete from table_name where line_name=
六、auto_increment
auto_increment: 当对应的字段,不给值,会自动地被系统触发,系统会从当前字段中已经有的最大值+1操作,得到一个新的不同的值。通常和主键搭配使用,作为逻辑主键。
自增长的特点:
~任何一个字段要做自增长,前提是本身是一个索引(key一栏有值)
~自增长字段必须是整数
~一张表最多只能有一个自增长
案例:

如果刚开始没有做任何插入,默认从1开始进行插入。
如果已经插入有数据,会从当前最大数据往后+1插入数据。

查看auto_increment:

之所以auto_increment 的值为1002是因为当我们在创建表加上auto_increment 这个选项时,mysqld会自动设置一个初始值,如果我们没有手动设置,这个值是1.当每次插入新数据,mysqld都会自动更新当前最大值+1为下一次插入时auto_increment的值。当然,这个值的初始值我们可以设定:

查看最后插入的id值:

索引:
在关系数据库中, 索引是一种单独的、物理的对数据库表中一列或多列的值进行排序的一种存储结构,它是某个表中一列或若干列值的集合和相应的指向表中物理标识这些值的数据页的逻辑指针清单。索引的作用相当于图书的目录,可以根据目录中的页码快速找到所需的内容。
索引提供指向存储在表的指定列中的数据值的指针,然后根据您指定的排序顺序对这些指针排序。 数据库使用索引以找到特定值,然后顺指针找到包含该值的行。这样可以使对应于表的SQL 语句执行得更快,可快速访问数据库表中的特定信息。
七、唯一键
一张表中往往有很多字段需要唯一性,数据不能重复,但是一张表中只能有一个主键:唯一键就可以解决表中有多个字段需要唯一性约束的问题。
案例:
主键是不能为空的,但是唯一键可以为空。
八、外键
外键用于定义主表和从表之间的关系:外键约束主要定义在从表上,主表则必须是有主键约束或unique约束。当定义外键后,要求外键列数据必须在主表的主键列存在或为null。
语法:
foreign key(字段名) references 主表(列)
案例:

主键表:

从表:

正常插入数据:

插入一个班级号为10的学生,因为没有这个班级,所以插入不成功:

当有外键约束数据关联时,是不能直接删除逐渐表数据的。当外键约束数据为空时才能删除。

