1.概念
约束是作用在表中列上的规则,用来限制加入的数据。保证了数据的正确性、有效性和完整性。
2.约束的分类
约束类型 | 说明 | 关键字 |
非空约束 | 保证数据不能有null值。 | not null |
唯一约束 | 保证数据各不相同。 | unique |
主键约束 | 主键是一行数据的唯一标识,要求非空且唯一。 | primary key |
外键约束 | 外键用来让两个表的数据之间建立连接。 | foreign key |
默认约束 | 保存数据时,未指定的值采用默认值。 | default |
检查约束 |
保证列中的值满足某一条件。 |
check |
②约束一般加在列的数据类型后面,同一列可加多个约束,用空格隔开。
③一张表里只能有一个主键。
③一张表里只能有一个主键。
3.外键约束语法
(1)添加外键约束
1)创建表时添加外键约束
create table 表名( 列名 数据类型, ..., [constraint] [外键名] foreign key (外键列名) references 主表(主表列名) );
2)建完表后,添加外键约束
alter table 表名 add constraint 外键名 foreign key (外键列表) references 主表(主表列名);
eg:创建员工表emp,并添加外键dep_id关联部门表dept的id。
create table emp( id int primary key, name varchar(20), age int, dep_id int, -- 添加外键dep_id关联dept表的id constraint fk_emp_dept foreign key (dep_id) references dept(id) );或已建好emp表:
alter table emp add constraint fk_emp_dept foreign key (dep_id) references dept(id);
(2)删除外键约束
alter table 表名 drop foreign key 外键名;【注意】删除外键时,用的是外键名而不是外键列表。