要求插入记录的时候,该字段不得为NULL。
写法:在字段后面写上not null。
create table T2(id int not null,name varchar(10) not null);
2、唯一性约束
多条记录的某个字段不得重复。
约束id字段不得重复 create table T3(id int,name varchar(10),unique uk1(id));
可以对多个字段进行唯一性限定,只有这些字段都相同的时候,才认为违反约束。
create table T4(id int,name varchar(10),unique uk1(id,name));
3、主键约束
一张条里用某个字段来唯一的识别某条记录。例如,学号。
主键=非空+唯一性。
create table T4(id int,name varchar(10),score int,primary key pk(id));
主键可以建立在多个字段上。但每个表只能有一个主键。
4、外键约束
在插入记录到某张表中时,要求某个字段必须要从另一张表中的字段选取。
也就是另一张表的某个字段的所有值是一个集合,这张表必须从该集合中选一个,不得超出集合。
create table chengji(id int,score int,foreign key fk1(id) references T4(id));
chengji表中的id必须从T4表中选取。
![](https://i-blog.csdnimg.cn/blog_migrate/cbf390d8b7b349abb945dde3e66493b6.png)
提供集合的表称为主表,创建了外键约束的表称为从表。要求主表的那个字段必须为主键,也就是非空+唯一。
外键约束特点:主表中已被从表引用的记录,不能先删除,要先删从表的,再删主表。
在外键约束后面加上on delete cascade,就可以在删除主表记录的时候,顺便删除从表的相关记录。
create table chengji(id int,score int,foreign key fk1(id) references T4(id) on delete cascade);
5、默认值
如果某条记录的某个字段未赋值,则使用默认值填充。
create table T5(id int,name varchar(20) default 'no_name');
6、无符号类型、0填充、使用中文
无符号类型:数据类型后加unsigned
数据类型不满的位置用0填充:zerofill
使用中文时最后添加character set utf8
create table T11(id int unsigned zerofill, name char(30) default '无名氏') character set utf8;