非空约束就是必须有数据,不允许为空。唯一约束就是指定的那个参数,它所在的一列里每个数据都不允许有重复。
非空约束
MySQL 非空约束(not null)指字段的值不能为空。对于使用了非空约束的字段,如果用户在添加数据时没有指定值,数据库系统就会报错。
添加非空约束
方式一:
<字段名><数据类型> not null;
举例:
-- 方式1,创建表时指定
create table t_user6 (
id int ,
name varchar(20) not null,
address varchar(20) not null
);
方式二:
方式2:alter table 表名 modify 字段 类型 not null;
举例:
create table t_user7 (
id int ,
name varchar(20) , -- 指定非空约束
address varchar(20) -- 指定非空约束
);
alter table t_user7 modify name varchar(20) not null;
alter table t_user7 modify address varchar(20) not null;
删除非空约束
在方式二的基础上,把后面的not null
去掉就删掉了非空约束。
-- alter table 表名 modify 字段 类型
alter table t_user7 modify name varchar(20) ;
alter table t_user7 modify address varchar(20) ;
演示
-- 选用mydb1数据库
use mydb1;
-- 创建一个表
-- 后面两个参数使用非空约束
create table user1(
id int ,
name varchar(20) not null, -- 非空约束
address varchar(20) not null -- 非空约束
);
-- 非空约束的参数如果不写值,会报错
insert into user1(id) value(1001); -- 不可以
下面这样的是可以的:
insert into user1(id, name, address) value(1001,'NULL','NULL');
此时的'NULL'表示一个字符串,而不是一个空值。
唯一约束
唯一约束(Unique Key)是指所有记录中字段的值不能重复出现。例如,为 id 字段加上唯一性约束后,每条记录的 id 值都是唯一的,不能出现重复的情况。
语法:
方式1:<字段名> <数据类型> unique
方式2: alter table 表名 add constraint 约束名 unique(列);
示例:
-- 创建表时指定
create table t_user8 (
id int ,
name varchar(20) ,
phonenumber varchar(20) unique -- 指定唯一约束
);
演示:
-- 选用mydb1数据库
use mydb1;
-- 创建一个表
-- 后面两个参数使用唯一约束
create table t_user8 (
id int ,
name varchar(20) ,
phone_number varchar(20) unique -- 指定唯一约束
);
insert into t_user8 values(1001,'张三',15555555)
但是要是再插入一个数据,号码与张三的一样,就会报错,因为phone_number这一些不允许有重复的数据,但是NULL空值是个例外。
删除唯一约束:
-- alter table <表名> drop index <唯一约束名>;
alter table t_user9 drop index unique_ph; -- 约束有名字的时候
alter table t_user9 drop index 列名; -- 约束没名字,就写列名,如id
声明:内容来源于B站视频《2022黑马程序员最新MySQL知识精讲+mysql实战案例_零基础mysql数据库入门到高级全套教程》,博客内容仅作学习参考使用。