约束(Constraint)
什么是约束?
在创建表的时候,可以给表的字段添加相应的约束,添加约束的目的是为了保证表中数据的合法性、有效性、完整性。
常见的约束有哪些?
非空约束(not null):约束的字段不能为NULL
唯一约束(unique):约束的字段不能重复
主键约束(primary key):约束的字段既不能为NULL,也不能重复(简称PK)
外键约束(foreign key):...(简称FK)
检查约束(check):注意Oracle数据库有check约束,但是mysql没有,目前mysql不支持该约束。
其他需要掌握的概念
列级约束
表级约束
非空约束
非空约束
not null
drop table if exists t_user;
create table t_user(
id int,
username varchar(255) not null,
password varchar(255)
);
insert into t_user(id,password) values(1,'123');
ERROR 1364 (HY000): Field 'username' doesn't have a default value
insert into t_user(id,username,password) values(1,'lisi','123');
注意:not null约束只有列级约束。没有表级约束。
唯一约束
唯一约束
unique
唯一约束修饰的字段具有唯一性,不能重复。但可以为NULL。
案例1:
给某一列添加unique
drop table if exists t_user;
create table t_user(
id int,
username varchar(255) unique // 列级约束
);
验证:
insert into t_user values(1,'zhangsan');
insert into t_user values(2,'zhangsan');
ERROR 1062 (23000): Duplicate entry 'zhangsan' for key 'username'
insert into t_user(id) values(2);
insert into t_user(id) values(3);
insert into t_user(id) values(4);
案例2:
给两个列或者多个列添加unique
drop table if exists t_user;
create table t_user(
id int,
usercode varchar(255) unique,
username varchar(255) unique
);
验证:
insert into t_user values(1,'111','zs');
insert into t_user values(2,'111','ls');
ERROR 1062 (23000): Duplicate entry '111' for key 'usercode'
案例3:
两个或多个字段联合起来添加1个约束unique 【表级约束】
drop table if exists t_user;
create table t_user(
id int,
usercode varchar(255),
username varchar(255),
unique(usercode,username) // 多个字段联合起来添加1个约束unique 【表级约束】
);
这种写法表示两个或多个字段联合起来之后具有唯一性(不能重复)
验证:
insert into t_user values(1,'111','zs');
insert into t_user values(2,'111','ls');
insert into t_user values(3,'222','zs');
select * from t_user;
insert into t_user values(4,'111','zs');
ERROR 1062 (23000): Duplicate entry '111-zs' for key 'usercode'
参考上边的两种写法,可做一个定义:
直接在字段后边添加的约束,叫“列级约束”;
在所有字段声明完毕之后再单独添加的约束,叫“表级约束”;
注意:not null约束只有列级约束。没有表级约束。