数据库约束数据库
1.基础限制ide
① 单一表内字节量总和不能超过65535,null 占用一个字节空间函数
② varchar存储255 之内字节占用一个字节表示长度,255以上本身则占用两个字节表示长度spa
③ 例如int(10)这里10指的是10字节宽度并不是数字10,且 utf8下 一字符=3字节,gbk下一字符=2字节 ,具体以下blog
数字类型索引
2.主键rem
主键关键字primary key ,规则 惟一,非空,索引凭据字符串
建立方式,例如:it
create table tb1(id int primary key not null auto_increment)engin=innodb chrset=utf8;innodb
create table tb1(id int not null auto_increment , primary key(id) )engin=innodb chrset=utf8;
修改主键时须要 使用关键字 modify ,也可设置主键起始值,或者给主键赋值,可是主键赋值以后再次插入数据时候会根据末尾ID进行自增+1
自增主键可设置起始值
create table tb1(id int not null auto_increment , primary key(id) )engin=innodb auto_increment=9 chrset=utf8;
修改主键使用drop关键字,修改主键使用modify
alter table tb1 drop primary key;
alter table tb1 modify id int;--这里是去掉了自增
查看刚刚生成的主键 last_insert_id() 函数,相似鱼SQL中的 select scope_identity;
select last_insert_id();
3.外键
外键关键字 foreign key(class_id) references tb1(id) ,外键能够为空,能够重复,不符合外键约束值则没法添加,且外键关系是相互的其中一方无效则外键无效
create table class(id int not null primary key auto_increment,name varchar(20))engine=innodb charset=utf8;
create table student(id not null primary key auto_increment,name varchar(20),class_id int,foreign(class_id) references class(id))engine=innodb charset=utf8;
insert into class (name) values('a','b','c');
insert into student(name,class_id) values('1',1),('2',2),('3',null);
删除外键使用关键字drop,添加外键使用add关键字,删除外键索引index
注意删除外键以前须要查看外键,直接删除外键名称则找不到外键
4.非空
限制字段不润许取NULL值,可是能够存空字符,修改非空与否 与修改表字段相同只是不添加限制条件
·5.惟一
限制字段取值,不能取出重复的值,容许null值,若字段中村财重复值则没法加入惟一,固然也能够设置多个字段同时拥有惟一约束
6.检测
check,该约束在数据插入的时候并不生效,因此通常忽略不计用法相似判断条件,通常会使用enum枚举来代替或者触发器trigger 。。then 代替。