【MySQL —— 数据库约束】


1. 什么是表约束

表约束是在创建表的时候,设计一些表的约束条件用来保证数据的合法性和数据的正确性。

2. 常见约束类型​

约束 说明
UNIQUE 保证某列的每行必须有唯一的值
NOT NULL 指示某列不能存储 NULL 值
DEFAULT 规定没有给列赋值时的默认值
PRIMARY KEY 确保某列(或两个列多个列的结合)有唯一标 识,有助于更容易更快速地找到表中的一个特定的记录
FOREIGN KEY 保证一个表中的数据匹配另一个表中的值的参照完整性
CHECK 保证列中的值符合指定的条件。对于MySQL数据库,对CHECK子句进行分析,但是忽略 CHECK子句

2.1 UNIQUE :唯一约束

创建表时指定 sn 列为唯一的:

drop table if exists student;
create table student (
 id int not null,
 sn int unique,
 name varchar(20)
);

ps:唯一约束字段可以插入 NULL ; 唯一约束字段的 NULL 可以插入多个。

2.2 NOT NULL :不为空约束

创建表时指定 id 列不为空:

drop table if exists student;
create table student (
 id int not null,
 sn int unique,
 name varchar(20)
);

2.3 DEFAULT :默认值约束

指定插入数据时,name 列为空,默认值“无名”:

drop table if exists student;
create table student (
	id int not null,
	sn int unique,
	name varchar(20) default '无名'
);

2.4 PRIMARY KEY :主键约束

指定 id 列为主键:
两种使用方式:

方法一:
drop table if exists student;
create table student (
	id int not null primary key,
	sn int unique,
	name varchar(20) default '无名'
);
方法二:
drop table if exists student;
create table student (
	id int not null,
	sn int unique,
	name varchar(20) default '无名',
	primary key (id,name)
);

第二种方式常用于多个字段作为主键,也就是联合主键。

❀主键的特征:

  • 主键可以有多个字段或单个字段组成;
  • 主键不能为空且唯一;
  • 一个表中只能有一个主键。

对于整数类型的主键,常配搭自增长auto_increment来使用。插入数据对应字段不给值时,使用最大值+1。
使用自增 auto_increment 的注意事项:

  • 一个表中只能由一个字段使用 auto_increment;
  • auto_increment 必须搭配主外键使用;
  • auto_increment 的类型只能时整数;
  • 查看自增值:show create table table_name;
  • 手动修改自增值的语句:alter table table_name auto_increment = n;

2.5 FOREIGN KEY :外键约束

外键用于关联其他表的主键或唯一键:

foreign key (字段名) references 主表()

外键约束同样也约束这父表,当父表种的某个记录被子表依赖的时候,此时尝试修改或删除都会失败。

外键约束的工作原理:在子表中插入新的记录时,就会先根据对应的值,在父表中先查询,查询到之后才能够执行后续的插入。外键要求父表中被依赖的这一列,必须要有索引,有了索引就能大大的提高查询速度。

2.6 CHECK约束

检查约束是保证列中的值符合指定的条件。检查约束在 MySQL 8.0.15 之前不起作用,只做了解。

drop table if exists test_user;
create table test_user (
 id int,
 name varchar(20),
 sex varchar(1),
 check (sex ='男' or sex='女')
);

活动地址:CSDN21天学习挑战赛

猜你喜欢

转载自blog.csdn.net/AlinaQ05/article/details/126121442