表的六种约束
- 主键约束
- 外键约束
- 唯一约束
- 默认约束
- 检查约束
- 非空约束
主键约束
primary key:
不能重复,不能为空,目的是为了做唯一标识符
一般情况要求主键自增。
不同的数据库,主键自增的方案不一样
Oracle:序列实现主键
MySQL:auto_increment
外键约束
foreign key:主要目的是为了描述不同表之间的关联关系
唯一约束
unique:该字段的值不能重复。
默认约束
为插入值或插入值为空,即使用默认值填充
default
检查约束
check:在SQL标准中,有检查约束
MySQL8.0之前默认不支持检查约束。
8.0之前定义添加检查约束,不报错不生效
之后开始支持检查约束。
非空约束
not null
必须要有值,不能为空
一个字段允许有多个约束。
示例:
create table t_user(
id int primary key,
name varchar(50) unique not null,
age int chexk(age>18) default 18,
gender char(2) check(gender in("F", "M"))
);
在MySQL8版本之前要使用检查约束的功能:
create table t_user(
id int primary key,
name varchar(50) unique not null,
# 范围判断只能使用触发器
age int chexk(age>18) default 18,
# 可以使用枚举类型替代检查约束
gender enum("F", "M")
);