MySQL基础篇(三):约束

131 阅读1分钟

约束

  1. 非空约束 not null :限制该字段的数据不能为null
  2. 唯一约束 unique :保证该字段数据是唯一的
  3. 主键约束 primary key :非空且唯一,主键是一行数据的唯一标识
  4. 默认约束 default : 如果保存数据时未指定字段的值则采用默认值
  5. 检查约束 check(8.0.16版本之后有): 保证字段值满足某个条件
  6. 外键约束 foreign key : 用来让两张表的数据之间建立连接,保证数据的一致性和完整性

案例展示:

image.png

create table user
(
    id     int primary key auto_increment comment '主键',
    name   varchar(10) not null unique comment '姓名',
    age    int check ( age > 0 and age <= 120 ) comment '年龄',
    status char(1) default '1' comment '状态',
    gender char(1)
) comment '用户表';

外键约束

image.png

  1. 添加/删除行为
1.添加外键
create table 表名(
    字段名 数据类型,
    ...
    [constraint] [外键名称] foreign key(外键字段名) references 主表(主表列名)
);
或者
alter table 表名 add constraint 外键名称 foreign key(外键字段名) references 主表(主表列名);
2.删除外键
alter table 表名 drop foreign key 外键名称;

注:具有外键的表称为子表(从表),外键所关联的表称为父表(主表)

  1. 删除/更新行为
语法:
alter table 表名 add constraint 外键名称 foreign key(外键字段) references 主表名(主表列名) on update cascade[set null] on delete cascade[set null]; #及联[置null]删除/更新

image.png