数据库之约束

一、为什么要有约束?

为了验证并确保数据库中数据格式的正确,引入约束的概念,约束可以规避以下问题:

  1. 冗余数据
  2. 失去数据完整性:如学生列表中,学号:1,2,3,3
  3. 数据缺少唯一表示(缺少id标识的学生列表中,重名学生的定位)
  4. 失去实体完整性: 比如学号数据的漏输,学号:1,2,空,4
  5. 失去引用的完整性:学生表45人,成绩表(以学号标识)出现了46的学号
  6. 失去域的完整性:性别栏,男,女,泰国。。。

 

二、数据库常用的约束

2.1主键约束

         让数据有唯一标识, 在创建表的时候

create table tableprimary_key( 
               id int  unsigned primary key auto_increment,)  
# unsigned 表正数
# auto_increment  自动增长

2.2自动增长  

auto_increment: 能保证无重复,无论是否出错都会自增一,删掉一个后,后面的序号也不会自动刷新(1,2,3,(4被删掉了)5,6,7)。

2.3唯一约束  

保证数据准确性

create table table_unique
( 
    id int unsigned primary key auto_increment,
    qqnumber char(18) unique
)

可以为多列设置唯一约束

2.4非空约束

保证数据不空

create table table_notnull
(   
    name varchar(30)  not null
)

2.5默认约束

给字段设置默认值

create table tbl_default(
      id int unsigned primary key auto_increment,
      age int unsigned default 0 not null);
# 默认0 不能为空

2.6检查约束(对mysql无效)

错误的数据就不应该被插入进去

create table tbl_check(
       id int unsigned primary key auto_increment,
       gender char(2) check('男' or '女')
)

2.7外键约束

要实现外键,必须先写主键(建立相应的主键表,外键表), 同样的要先删除外键,再删除主键。

# 主键表
create table Department(
       Depid int unsigned primary key auto_increment,
       DepName varchar(30)
)


# 外键表
create talble Employees(
       id int unsigned primary key auto_increment,
       Depid int unsigned,
       foreign key(Depid) references Department(Depid)
)

 #  三、建表后添加约束

#  未完待续

猜你喜欢

转载自blog.csdn.net/Scrat_Kong/article/details/81562048