MySQL之约束
约束用来保证数据的完整性和一致性。
约束类型包括:
非空约束
主键约束
唯一约束
默认约束
外键约束
-
非空约束
null :字段值可以为空 not null:字段值不可以为空
-
主键约束 primary key
每张表只有一个主键约束 主键保证了记录的唯一性 主键自动为not null 主键字段允许赋值,但不允许重复 auto_increment必须与主键使用,但主键可以不与auto_increment一起使用
-
唯一约束 unique key
唯一约束的字段可以设为null 每张表中可以有多个唯一约束
-
默认约束
当插入记录时,如果没有明确为字段赋值,则自动赋默认值
例子:
create table t1 (
id smallint unsigned auto_increment primary key,
username varchar(20) unique key,
sex enum(‘1’,‘2’,‘3’) default ‘3’
); -
外键约束
实现一对一或一对多关系
有外键的表称为子表,子表参考的表称为父表
父表和子表使用相同的存储引擎,而且禁止使用临时表
存储引擎只能为InnoDB
外键列和参考列必须具有相似的数据类型。其中数字的长度和是否有符号位必须相同,而字符的长度可以不同
外键列和参考列必须创建索引,如果外键列不创建索引的话,MySQL会自动创建索引。create table provinces(
id smallint unsigned auto_increment primary key,
pname varchar(20) not null
);create table users(
id smallint unsigned auto_increment primary key,
username varchar(20) unique key,
pid smallint unsigned,
foreign key (pid) references provinces (id)
);插入记录时,先在父表中添加记录,然后在子表中添加记录。
insert provinces (pname) values (‘A’);
insert provinces (pname) values (‘B’);
insert provinces (pname) values (‘C’);insert users1 (username,pid) values (‘Tom’,3);
insert users1 (username,pid) values (‘John’,1);
insert users1 (username,pid) values (‘rose’,3); -
为数据表添加约束
添加主键约束:
alter table table_name add [constraint [symbol]] primary key [index_type] (index_column_name,...)
例子:
alter table users2 add primary key (id); //将id列设为主键约束
alter table users2 add constraint pk_users2_id primary key (id); //给约束起名字添加唯一约束:
alter table table_name add [constraint [symbol]] unique [index|key] [index_name] [index_type] (index_column_name,...)
例子:
alter table users2 add unique key (username); //将username列设为唯一约束添加外键约束:
alter table table_name add [constraint [symbol]] foreign key [index_name] (index_column_name,...) reference_definition
例子:
alter table users2 add foreign key (pid) references provinces(id); //为pid添加外键约束添加/删除默认约束
alter table table_name alter [column] column_name {set default literal | drop default}
例子:
alter table users2 alter age set default 10; //添加默认约束
alter table users2 alter age drop default; //删除默认约束 -
删除数据表约束
删除主键约束:
alter table table_name drop primary key;
删除唯一约束:
alter table table_name drop {index|key} index_name;
例子:
alter table users2 drop index username; //删除username的唯一约束删除外键约束:
alter table table_name drop foreign key (外键约束名);
例子:
alter table users2 drop foreign key users2_idfk_1;可以通过show create table users2;找到外键约束名