非空约束 not null
create table student_tb(
id int not null , 非空约束(数据不允许为空)
name varchar ( 255 ) null 显式指定允许为空
) ;
- 添加非空约束
alter table 表名 modify column 属性名 属性类型 not null ;
alter table student_tb modify column name varchar ( 255 ) not null ;
- 删除非空约束
alter table 表名 modify column 属性名 属性类型;
alter table student_tb modify column id int ;
唯一性约束 unique
create table teacher_tb(
id int not null unique , 唯一性约束(数据存在必唯一,允许为 null )
另一种写法
id int ,
unique ( id)
name varchar ( 255 ) not null ,
- 约束关键字 constraint
给约束起名字,方便删除
constraint 约束名 约束类型
constraint id_unique unique ( name) ,
age int
) ;
- 添加唯一性约束
alter table 表名 add constraint [ 约束名] unique (属性名);
alter table teacher_tb add constraint age_unique unique ( age) ;
- 删除唯一性约束
alter table 表名 drop index 属性名;
alter table teacher_tb drop index age_unique;
自增长约束 auto_increment
create table student_tb(
id int primary key auto_increment , 自增长约束必须和主键一起使用
age int
) [ auto_increment = 2 ] ; 可以自己设置初始值,默认为 1 开始
- 添加自增长约束
alter table 表名 modify column 属性名 属性类型 primary key auto_increment ;
默认值约束 default
create table course_tb(
subject varchar ( 20 ) default math,
teacher varchar ( 20 )
) ;
- 添加默认值约束
alter table 表名 modify column 属性名 属性类型 default 默认值;
alter table course_tb modify column teacher varchar ( 20 ) default '小雨滴' ;
- 删除默认值约束
alter table 表名 modify column 属性名 属性类型;
alter table course_tb modify column teacher varchar ( 20 ) ;
主键约束 primary key
主键约束的特点
- 非空约束 not null
- 唯一约束 unique
- 每个表只能有一个主键约束
- 多列联合的主键约束,联合主键的值不能重复
- 列级定义
create table student_tb(
id int primary key ,
age int
) ;
- 表级定义
create table student_tb(
id int ,
age int ,
constraint id_primary primary key ( id)
) ;
- 复合主键(表级定义)
create table student_tb(
id int ,
age int ,
primary key ( id, age)
) ;
- 添加主键约束
alter table 表名 add constraint 主键名 primary key ( 属性名) ;
create table student_tb(
id int ,
age int ,
) ;
alter table student_tb add constraint primary_key primary key ( id) ;
- 删除主键约束
alter table 表名 drop primary key ;
alter table student_tb drop primary key ;
外键约束 foreign key
- 什么是外键
当有两个表 A、B , id 是 A 的主键, 而 B 中也有 id 字段,则 id 就是表 B 的外键
一张表可以有多个外键
- 添加外键约束(列级定义)
foreign key ( 属性名) references 被引用表名( 被引用表主键名)
create table student_tb(
stu_id int primary key ,
name varchar ( 20 ) ,
class int
) ;
create table inform_tb(
grade int ,
id int ,
foreign key ( id) references student_tb( stu_id) ;
) ;
- 添加外键约束
alter table 表名 add constraint 约束名 foreign key ( 属性名) references 被引用表名( 主键名) ;
alter table inform_tb add constraint id_foreign foreign key ( id) references student_tb( stu_id) ;
- 删除外键约束
alter table 表名 drop foreign key 约束名;
alter table inform_tb drop foreign key id_foreign;