目录

mysql 表的完整性约束

约束概念

为了防止不符合规范的数据进入数据库,在用户对数据进行插入、修改、删除等操作时,DBMS自动按照一定的约束条件对数据进行监测,
使不符合规范的数据不能进入数据库,以确保数据库中存储的数据正确、有效、相容。 
约束条件与数据类型的宽度一样,都是可选参数,主要分为以下几种:
# NOT NULL :非空约束,指定某列不能为空; 
# UNIQUE : 唯一约束,指定某列或者几列组合不能重复
# PRIMARY KEY :主键,指定该列的值可以唯一地标识该列记录
# FOREIGN KEY :外键,指定该行记录从属于主表中的一条记录,主要用于参照完整性

unsigned 设置某一个数字无符号 (整数类型 ,浮点类型不能是unsigned)

#unsigned 就是将数字类型无符号化, 例如 int 型的范围:-2^31 ~ 2^31 - 1,而unsigned int的范围:0 ~ 2^32。
not null default create table t2(id int not null,name char(12) not null,age int default 18,
gender enum('male','female') not null default 'male');

not null 某一个字段不能为空(严格模式会影响非空设置的效果)

#not null示例
mysql> create table t12 (id int not null);
Query OK, 0 rows affected (0.02 sec)

mysql> select * from t12;
Empty set (0.00 sec)

mysql> desc t12;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
row in set (0.00 sec)

#不能向id列插入空元素。 
mysql> insert into t12 values (null);
ERROR 1048 (23000): Column 'id' cannot be null

mysql> insert into t12 values (1);
Query OK, 1 row affected (0.01 sec)

#not null不生效

#设置严格模式:
    不支持对not null字段插入null值
    不支持对自增长字段插入值
    不支持text字段有默认值

#直接在mysql中生效(设置在内存,重启失效):
mysql>set sql_mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION";

#配置文件添加(永久生效):
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

default 给某个字段设置默认值(设置默认值)

#我们约束某一列不为空,如果这一列中经常有重复的内容,就需要我们频繁的插入,这样会给我们的操作带来新的负担,
#于是就出现了默认值的概念。
#默认值,创建列时可以指定默认值,当插入数据时如果未主动设置,则自动添加默认值
#not null + default 示例
mysql> create table t13 (id1 int not null,id2 int not null default 222);
Query OK, 0 rows affected (0.01 sec)

mysql> desc t13;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id1   | int(11) | NO   |     | NULL    |       |
| id2   | int(11) | NO   |     | 222     |       |
+-------+---------+------+-----+---------+-------+
rows in set (0.01 sec)

# 只向id1字段添加值,会发现id2字段会使用默认值填充
mysql> insert into t13 (id1) values (111);
Query OK, 1 row affected (0.00 sec)

mysql> select * from t13;
+-----+-----+
| id1 | id2 |
+-----+-----+
| 111 | 222 |
+-----+-----+
row in set (0.00 sec)

# id1字段不能为空,所以不能单独向id2字段填充值;
mysql> insert into t13 (id2) values (223);
ERROR 1364 (HY000): Field 'id1' doesn't have a default value

# 向id1,id2中分别填充数据,id2的填充数据会覆盖默认值
mysql> insert into t13 (id1,id2) values (112,223);
Query OK, 1 row affected (0.00 sec)

mysql> select * from t13;
+-----+-----+
| id1 | id2 |
+-----+-----+
| 111 | 222 |
| 112 | 223 |
+-----+-----+
rows in set (0.00 sec)

unique 设置某一个字段不能重复 (唯一约束)

create table t3(id int unique,username char(12) unique,password char(18));

# 联合唯一  unique(字段1,字段2)
create table t4(id int,ip char(15),server char(10),port int,unique(ip,port));
  • 联合唯一写法unique( 字段名,字段名)

mysql 表的完整性约束 Mysql 第1张

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
#unique示例
方法一:
create table department1(
id int,
name varchar(20) unique,
comment varchar(100)
);


方法二:
create table department2(
id int,
name varchar(20),
comment varchar(100),
unique(name)
);


mysql> insert into department1 values(1,'IT','技术');
Query OK, 1 row affected (0.00 sec)
mysql> insert into department1 values(1,'IT','技术');
ERROR 1062 (23000): Duplicate entry 'IT' for key 'name'
    
#not null 和unique的结合
mysql> create table t1(id int not null unique);
Query OK, 0 rows affected (0.02 sec)

mysql> desc t1;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   | PRI | NULL    |       |
+-------+---------+------+-----+---------+-------+
row in set (0.00 sec)

#联合唯一
create table service(
id int primary key auto_increment,
name varchar(20),
host varchar(15) not null,
port int not null,
unique(host,port) #联合唯一
);

mysql> insert into service values
    -> (1,'nginx','192.168.0.10',80),
    -> (2,'haproxy','192.168.0.20',80),
    -> (3,'mysql','192.168.0.30',3306)
    -> ;
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> insert into service(name,host,port) values('nginx','192.168.0.10',80);
ERROR 1062 (23000): Duplicate entry '192.168.0.10-80' for key 'host'

auto_increment 设置某一个int类型的字段 自动增加 (自增字段 必须是数字 且 必须是唯一的)

  • auto_increment自带not null效果(非空约束)
  • 设置条件 int unique
  • not null 不能为空 mysql 5.4版本不生效要重新配置 mysql 5.6以上默认生效
create table t5(id int unique auto_increment,username char(10),password char(18));
  • 默认表结构都要有id,一般第一个字段就是id,且设置自增

mysql 表的完整性约束 Mysql 第2张

primary key 设置主键 (这一个字段非空且唯一)

  • 约束这个字段 非空(not null) 且 唯一(unique)
  • 一张表只能由有一个主键,一张表最好设置一个主键
 primary key(字段1,字段2)#主键为了保证表中的每一条数据的该字段都是表格中的唯一值。换言之,
它是用来独一无二地确认一个表格中的每一行数据。
#主键可以包含一个字段或多个字段。当主键包含多个栏位时,称为组合键 (Composite Key),也可以叫联合主键。
#主键可以在建置新表格时设定 (运用 CREATE TABLE 语句),或是以改变现有的表格架构方式设定 (运用 ALTER TABLE)。
#主键必须唯一,主键值非空;可以是单一字段,也可以是多字段组合。


#你指定的第一个非空且唯一的字段会被定义成主键
create table 表(id int not null unique,name char(12) not null unique);

#设置主键方法
create table 表(id int primary key,name char(12) not null unique);

# 联合主键 primary key(字段1,字段2)
create table t4(id int,ip char(15),server char(10), port int,primary key(ip,port));

指定的第一个非空且唯一的字段会被默认定义成主键

mysql只识别;号为结束语句,换行符不识别,可以执行

foreign key 外键 (外键,涉及到两张表,数据类型一样,且有唯一约束)

  • 级联操作:on update cascade on delete cascade
#多表 :
#假设我们要描述所有公司的员工,需要描述的属性有这些 : 工号 姓名 部门
#公司有3个部门,但是有1个亿的员工,那意味着部门这个字段需要重复存储,部门名字越长,越浪费
#解决方法: 我们完全可以定义一个部门表 然后让员工信息表关联该表,如何关联,即foreign key

###############################创造外键的条件#################################
mysql> create table departments (dep_id int(4),dep_name varchar(11));
Query OK, 0 rows affected (0.02 sec)

mysql> desc departments;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| dep_id   | int(4)      | YES  |     | NULL    |       |
| dep_name | varchar(11) | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
rows in set (0.00 sec)

# 创建外键不成功
mysql> create table staff_info (s_id int,name varchar(20),dep_id int,foreign key(dep_id) references departments(dep_id));
ERROR 1215 (HY000): Cannot add foreign key 

# 设置dep_id非空,仍然不能成功创建外键
mysql> alter table departments modify dep_id int(4) not null;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc departments;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| dep_id   | int(4)      | NO   |     | NULL    |       |
| dep_name | varchar(11) | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
rows in set (0.00 sec)

mysql> create table staff_info (s_id int,name varchar(20),dep_id int,foreign key(dep_id) references departments(dep_id));
ERROR 1215 (HY000): Cannot add foreign key constraint

# 当设置字段为unique唯一字段时,设置该字段为外键成功
mysql> alter table departments modify dep_id int(4) unique;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc departments;                                                                                                       +----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| dep_id   | int(4)      | YES  | UNI | NULL    |       |
| dep_name | varchar(11) | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
rows in set (0.01 sec)

mysql> create table staff_info (s_id int,name varchar(20),dep_id int,foreign key(dep_id) references departments(dep_id));
Query OK, 0 rows affected (0.02 sec)

#表类型必须是innodb存储引擎,且被关联的字段,即references指定的另外一个表的字段,必须保证唯一
create table department(
id int primary key,
name varchar(20) not null
)engine=innodb;

#dpt_id外键,关联父表(department主键id),同步更新,同步删除
create table employee(
id int primary key,
name varchar(20) not null,
dpt_id int,
foreign key(dpt_id)
references department(id)
on delete cascade  # 级连删除
on update cascade # 级连更新
)engine=innodb;


#先往父表department中插入记录
insert into department values
(1,'教质部'),
(2,'技术部'),
(3,'人力资源部');


#再往子表employee中插入记录
insert into employee values
(1,'xpn',1),
(2,'gkf',2),
(3,'tiandan',2),
(4,'goudan',2),
(5,'gandan',3),
(6,'敏敏',3),
(7,'皮卡丘',3),
(8,'程咬金',3),
(9,'程咬银',3)
;


#删父表department,子表employee中对应的记录跟着删
mysql> delete from department where id=2;

########################################外键操作示例############################################

#更新父表department,子表employee中对应的记录跟着改
mysql> update department set id=2 where id=3;

##################################on delete(了解)###################################
. cascade方式
在父表上update/delete记录时,同步update/delete掉子表的匹配记录 

   . set null方式
在父表上update/delete记录时,将子表上匹配记录的列设为null
要注意子表的外键列不能为not null  

   . No action方式
如果子表中有匹配的记录,则不允许对父表对应候选键进行update/delete操作  

   . Restrict方式
同no action, 都是立即检查外键约束

   . Set default方式
父表有变更时,子表将外键列设置成一个默认的值 但Innodb不能识别

references 级联删除和更新

#创建员工表
create table staff(id  int primary key auto_increment,age int,gender  enum('male','female'),salary  float(8,2),hire_date date,post_id int,foreign key(post_id) references post(pid));
作 者: 郭楷丰 出 处: https://www.cnblogs.com/guokaifeng/ 声援博主:如果您觉得文章对您有帮助,可以点击文章右下角 推荐一下。您的鼓励是博主的最大动力! 自 勉:生活,需要追求;梦想,需要坚持;生命,需要珍惜;但人生的路上,更需要坚强。 带着感恩的心启程,学会爱,爱父母,爱自己,爱朋友,爱他人。
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄