数据库基础(四)
MySql-约束
约束作用:保证数据的准确和可靠性,从而实现数据完整性。
数据完整性
- 域完整性
- 列限制
- 如:年龄必须是数字,性别只能是男或者女
- 实体完整性
- 实体限制或叫行限制
- 如:相同的数据不能重复插入
- 引用完整性
- 外键
- 自定义完整性
- 根据业务需求,自行定义限制
- 保证数据的完整,就是实现完整性约束
约束
- 主键
- 唯一的标识表中的每一行
- 实际组成为:唯一约束+非空约束+索引(提高查询速度)
- 一张表最多只能有一个主键
- 关键字
- PRIMARY KEY
- 创建
- 方式1:create table student(
id int,
name varchar(10),
age int,
tel varchar(11),
sex char(1),
constraint 主键名 primary key(id)
);- 方式2:alter table student add constraint 主键名 primary key(id)
- 方式1:create table student(
- 删除:alter table student drop primary key
- 外键
- 限定一张表中某一列的值必须来源于另一张表中的某一列,另一张表的列必须有唯一约束
- 关键字
- foreign key references
- 创建:
- 方式一:create table student(
cid int,
name varchar(10),
age int,
tel varchar(11),
sex char(1),
constraint 外键名 foreign key(cid) references class(id)
);
这里的class的id列必须在class中唯一。 - 方式二:alter table student add constraint 外键名 foreign key(cid) references class(id);
- 方式一:create table student(
- 删除:alter table student drop froeign key 外键名;
- 唯一性
- 关键字
- unqiue
- 创建
- 方式一:建表时创建
- create table class(
id int,
name varchar(10) not null,
constraint 约束名 unique(id)
); - 方式2:alter table class add constraint 约束名 unqiue;
- create table class(
- 方式一:建表时创建
- 删除
- alter table class drop index 约束名;
- 关键字
- 非空
- 保证数据不为null
- 关键字
- not null
- 创建
- 方式一:create table student(
id int,
name varchar(10) not null
); - 方式二:alter table student modify name varchar(10) not null;
- 方式一:create table student(
- 删除:alter table student modify name varchar(10) ;
- 自增
- 自动生成值,值自动添加
- 只能添加到主键列,且类型必须是整型
- 关键字
- auto_increment
- 创建
- 方式一:cretae table student(
id int primary key auto_increment
); - 方式二:用modify重新定义一下类似上面的非空
- 方式一:cretae table student(
- 删除:类似上面的非空,重新定义一下
- 默认
- 为某列设置默认值
- 关键字
- default
- 创建
- 方式一:create table student(
id int;
name varchar(10),
tel char(11) default ‘13111111111’
); - 方式二及删除类似非空和自增
- 方式一:create table student(