前言
本章主要讲述mysql的约束
一.概述
约束是添加在列上的,且用来约束列的
二.常见约束
NOT NULL:非空,该字段的值必填
UNIQUE:唯一,该字段的值不可重复
DEFAULT:默认,该字段的值不用手动插入有默认值
PRIMARY KEY:主键,该字段的值不可重复并且非空 unique+not null
FOREIGN KEY:外键,该字段的值引用了另外的表的字段
1.主键约束(唯一标识)
特点:非空、唯一、被引用
当表的某一列被指定为主键后,该列就不能为空且不能有重复值出现
1)创建表时指定主键的两种方式
-
语法一
create table 表名(
字段名 字段类型 Primary key,
字段名 字段类型
);
例:
create table stu(
sname varchar(20) Primary key,
age int
);
-
语法二、
create table 表名(
字段名 字段类型 ,
字段名 字段类型,
Primary key(sname)
);
例:
create table stu(
sname varchar(20) ,
age int,
Primary key(sname)
);
2)修改表时指定主键
alter table 表名 add primary key(字段名);
3)删除主键
alter table 表名 drop primary key;
2.主键自增长( Primary key auto_increment)
由于主键列的特性:必须唯一、非空,所以我们通常指定主键类型为整型
然后设置其自动增长,这样则可保证插入数据是主键列的唯一非空性.
1)创建表时指定主键增长
create table stu(
id int Primary key auto_increment
sname varchar(20),
age int
);
2)修改表时设置主键自增长
语法:alter table 表 change column 字段名 字段类型 auto_increment
例:
alter table stu change sname sname int auto_increment;
3)修改表时删除主键自增长
语法:alter table 表 change column 字段名 字段类型
例:
alter table stu change sname sname int;
3.非空约束(not null)
因为某一些列不能设置为null值,所以可以对列添加非空约束
例:
create table stu(
id int Primary key auto_increment
sname varchar(20),
age int not null
);
4.唯一约束(Unique)
例:
create table stu(
id int Primary key auto_increment
sname varchar(20),
age int not null(unique)
);
5.外键约束(foreign key(外键列名))
-
特点
1、外键必须是另一个表的主键的值(外键引用主键)、
2、外键可重复
3、外键可为空
4、一张表中可有多个外键 -
语法
Constraint 约束名称 Foreign key(外键列名) References 关联表(关联表的主键)
1)创建表时指定外键约束
create table emp(
emptno int primary key,
...
deptno int,
Constraint fk_emp foreign key(mgr) References dept(deptno)
);
2)修改表时添加外键约束
- 语法:alter table 表名 add【 constraint 约束名】 foreign key(字段名) references
主表(被引用列);
例:
alter table emp add Constraint fk_emp_deptno foreign key(deptno) References dept(deptno);
3)修改表时删除外键约束
-
语法:alter table 表名 drop foreign key 约束名;
alter table emp drop foreign key fk_emp_deptno ;