约束的作用:保证数据的完整性和一致性
1.not null与default
如果单独设置了not null,不能插入空值
如果设置了not null和default,可以插入空值,插入的值变为default的值
create table student(
id int not null,
name varchar(50) not null,
age int(3) unsigned not null default 18,
sex enum("man","woman") default "man",
fav set("singing","dancing","basketball") default "basketball"
);
insert into student(id,name) values(1,"yhr");
2.unique
单列唯一:一个表中只有一个字段是唯一的
create table student(
id int unique,
name varchar(20) not null
);
create table student(
id int;
name varchar(20) not null
unique(id)
);
insert into student(id,name) values(1,"yhr");
insert into student(id,name) values(1,"alex"); 这个记录不能插入,因为id已经存在
多列唯一:一个表中有多个字段是唯一的,且字段之间没有关系,只要有一列相同就不能插入
create table student(
id int unique,
name varchar(20) unique
);
create table student(
id int,
name varchar(20),
unique(id),
unique(name)
);
insert into student(id,name) values(1,"yhr");
insert into student(id,name) values(1,"alex"); 这个记录不能插入,因为id已经存在
insert into student(id,name) values(2,"yhr"); 这个记录不能插入,因为name已经存在
联合唯一:多个字段相对应的内容不能相同,多列相同时不能插入
create table student(
id int,
name varchar(20),
unique(id,name)
);
insert into student(id,name) values(1,"alex");
insert into student(id,name) values(1,"wusir"); 可以插入
insert into student(id,name) values(1,"alex"); 不能插入
3.primary key
单列主键:不为空,且是唯一的 not null+unique
create table student(
id int unsigned primary key,
name char(20) unique
);
insert into student(id,name) values(1,"alex");
insert into student(id,name) values(1,"wusir");不能插入
insert into student(id,name) values(2,"alex");不能插入
联合主键:不能为空,多对多
create table studnet(
id int unsigned,
name unique,
primary key(id,name)
);
insert into student(id,name) values(1,"alex");
insert into student(id,name) values(2,"alex"); 可以插入
insert into student(id,name) values(1,"wusir"); 可以插入
4.auto_increment
auto_increment自增长
create table student(
id int primary key auto_increment,
name char(10) unique,
sex enum("man","woman") default "man"
);
insert student(name) values("alex"); id为1
insert student(name) values("wusir"); id为2
delete from student;
insert student(name) values("mjj"); id为3
delete删除表的记录,但是并不会影响id的自增长顺序,id增长到2,删除以前的记录,并不会改变增长到的顺序,所以还是从3开始
truncate table student; 这样清空表,id从0开始
另外:我们可以设置auto_increment的起始值和增长值
set session auto_increment_increment=5; 设置步长为5(会话)
set global auto_increment_increment=5;设置步长(全局)
set global auto_increment_offset=3; 设置起始值为3
如果起始值大于步长,起始值会被忽略