0

0

mysql完整性约束详细介绍

王林

王林

发布时间:2019-08-28 14:06:09

|

2966人浏览过

|

来源于博客园

转载

一、介绍

约束条件与数据类型的宽度一样,都是可选参数

作用:用于保证数据的完整性和一致性

主要分为:

PRIMARY KEY (PK)    #标识该字段为该表的主键,可以唯一的标识记录

FOREIGN KEY (FK)    #标识该字段为该表的外键

NOT NULL    #标识该字段不能为空

UNIQUE KEY (UK)    #标识该字段的值是唯一的

AUTO_INCREMENT    #标识该字段的值自动增长(整数类型,而且为主键)

DEFAULT    #为该字段设置默认值

UNSIGNED #无符号

ZEROFILL #使用0填充

说明:

#1. 是否允许为空,默认NULL,可设置NOT NULL,字段不允许为空,必须赋值 

#2. 字段是否有默认值,缺省的默认值是NULL,如果插入记录时不给字段赋值,此字段使用默认值

 sex enum('male','female') not null default 'male' 

 #必须为正值(无符号) 不允许为空 默认是20age int unsigned NOT NULL default 20 

# 3. 是否是key 

主键 primary key

外键 foreign key 

索引 (index,unique...)

二、NOT NULL 和DEFAULT

是否可空,null表示空,非字符串
not null - 不可空
null - 可空

默认值,创建列时可以指定默认值,当插入数据时如果未主动设置,则自动添加默认值

create table tb1(
    nid int not null defalut 2,    
    num int not null);

注意:

1、默认值可以为空

2、设置not null,插入值时不能为空

3、设置id字段有默认值后,则无论id字段是null还是not null,都可以插入空,插入空默认填入default指定的默认值

三、UNIQUE

中文翻译:不同的。在mysql中称为单列唯一

举例说明:创建公司部门表(每个公司都有唯一的一个部门)

mysql> create table department(
    -> id int,
    -> name char(10)
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> insert into department values(1,'IT'),(2,'IT');
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0mysql> select * from department;
+------+------+| id   | name |
+------+------+|    1 | IT   |
|    2 | IT   |
+------+------+2 rows in set (0.00 sec)
# 发现: 同时插入两个IT部门也是可以的,但这是不合理的,所以我们要设置name字段为unique 解决这种不合理的现象。

接下来,使用约束条件unique,来对公司部门的字段进行设置。

#第一种创建unique的方式#例子1:create table department(
    id int,
    name char(10) unique
);
mysql> insert into department values(1,'it'),(2,'it');
ERROR 1062 (23000): Duplicate entry 'it' for key 'name'
#例子2:create table department(
    id int unique,
    name char(10) unique
);
insert into department values(1,'it'),(2,'sale');
#第二种创建unique的方式create table department(
    id int,
    name char(10) ,    unique(id),    unique(name)
);
insert into department values(1,'it'),(2,'sale');

联合唯一:

文心快码
文心快码

文心快码(Comate)是百度推出的一款AI辅助编程工具

下载
# 创建services表mysql> create table services(
        id int,
        ip char(15),
        port int,
        unique(id),
        unique(ip,port)
       );
Query OK, 0 rows affected (0.05 sec)

mysql> desc services;
+-------+----------+------+-----+---------+-------+
| Field | Type      | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id        | int(11)   | YES   | UNI  | NULL       |             
| ip        | char(15) | YES   | MUL  | NULL       |          
| port    | int(11) | YES   |          | NULL       |             
|+-------+----------+------+-----+---------+-------+|
3 rows in set (0.01 sec)
#联合唯一,只要两列记录,有一列不同,既符合联合唯一的约束mysql> insert into services values
       (1,'192,168,11,23',80),
       (2,'192,168,11,23',81),
       (3,'192,168,11,25',80);
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0
mysql> select * from services;
+------+---------------+------+
| id   | ip            | port |
+------+---------------+------+
|    1 | 192,168,11,23 |   80 |
|    2 | 192,168,11,23 |   81 |
|    3 | 192,168,11,25 |   80 |
+------+---------------+------+
3 rows in set (0.00 sec)

mysql> insert into services values (4,'192,168,11,23',80);
ERROR 1062 (23000): Duplicate entry '192,168,11,23-80' for key 'ip'

四、PRIMARY KEY

在MySQL的一个表中只有唯一的一个主键,不能有多列主键,但可以有复合主键

一个表中可以:

单列做主键
多列做主键(复合主键)

约束:等价于 not null unique,字段的值不为空且唯一

存储引擎默认是(innodb):对于innodb存储引擎来说,一张表必须有一个主键。

单列主键:

# 创建t14表,为id字段设置主键,唯一的不同的记录create table t14(
    id int primary key,
    name char(16)
);
insert into t14 values(1,'xiaoma'),(2,'xiaohong');

mysql> insert into t14 values(2,'wxxx');
ERROR 1062 (23000): Duplicate entry '6' for key 'PRIMARY'
#   not null + unique的化学反应,相当于给id设置primary key
create table t15(
    id int not null unique,
    name char(16)
);
mysql> create table t15(
    -> id int not null unique,
    -> name char(16)
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> desc t15;
+-------+----------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id        | int(11)  | NO     | PRI | NULL       |             |
| name   | char(16) | YES  |         | NULL       |             |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.02 sec)

复合主键:

create table t16(
    ip char(15),
    port int,
    primary key(ip,port)
);
insert into t16 values('1.1.1.2',80),('1.1.1.2',81);

五、AUTO_INCREMENT

约束:约束的字段为自动增长,约束的字段必须同时被key约束

create table student(
id int primary key auto_increment,
name varchar(20),
sex enum('male','female') default 'male'
);

1、不指定id,则自动增长

2、也可以指定id

3、对于自增的字段,在用delete删除后,再插入值,该字段仍按照删除前的位置继续增长

auto_increment_incrementauto_increment_offset的区别

查看可用的 开头auto_inc的词
mysql> show variables like 'auto_inc%';
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| auto_increment_increment | 1     |
| auto_increment_offset    | 1     |
+--------------------------+-------+
rows in set (0.02 sec)
# 步长auto_increment_increment,默认为1
# 起始的偏移量auto_increment_offset, 默认是1

 # 设置步长 为会话设置,只在本次连接中有效
 set session auto_increment_increment=5;

 #全局设置步长 都有效。
 set global auto_increment_increment=5;

 # 设置起始偏移量
 set global  auto_increment_offset=3;

#强调:If the value of auto_increment_offset is greater than that of auto_increment_increment, 
the value of auto_increment_offset is ignored. 
翻译:如果auto_increment_offset的值大于auto_increment_increment的值,则auto_increment_offset的值会被忽略 

# 设置完起始偏移量和步长之后,再次执行show variables like'auto_inc%';
发现跟之前一样,必须先exit,再登录才有效。

mysql> show variables like'auto_inc%';
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| auto_increment_increment | 5     |
| auto_increment_offset    | 3     |
+--------------------------+-------+
rows in set (0.00 sec)

#因为之前有一条记录id=1
mysql> select * from student;
+----+---------+------+
| id | name    | sex  |
+----+---------+------+
|  1 | xiaobai | male |
+----+---------+------+
row in set (0.00 sec)
# 下次插入的时候,从起始位置3开始,每次插入记录id+5
mysql> insert into student(name) values('ma1'),('ma2'),('ma3');
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0
mysql> select * from student;
+----+---------+------+
| id | name    | sex  |
+----+---------+------+
|  1 | xiaobai | male |
|  3 | ma1     | male |
|  8 | ma2     | male |
| 13 | ma3     | male |
+----+---------+------+
auto_increment_increment和 auto_increment_offset

清空表区分deletetruncate的区别:

delete from t1; #如果有自增id,新增的数据,仍然是以删除前的最后一样作为起始。

truncate table t1;数据量大,删除速度比上一条快,且直接从零开始。

六、FOREIGN KEY

公司有3个部门,但是有1个亿的员工,那意味着部门这个字段需要重复存储,部门名字越长,越浪费。

这个时候,

解决方法:

我们完全可以定义一个部门表

然后让员工信息表关联该表,如何关联,即foreign key

创建两张表操作:

#1.创建表时先创建被关联表,再创建关联表
# 先创建被关联表(dep表)
create table dep(
    id int primary key,
    name varchar(20) not null,
    descripe varchar(20) not null
);
#再创建关联表(emp表)
create table emp(
    id int primary key,
    name varchar(20) not null,
    age int not null,
    dep_id int,
    constraint fk_dep foreign key(dep_id) references dep(id) 
);
#2.插入记录时,先往被关联表中插入记录,再往关联表中插入记录
insert into dep values
(1,'IT','IT技术有限部门'),
(2,'销售部','销售部门'),
(3,'财务部','花钱太多部门');
insert into emp values
(1,'zhangsan',18,1),
(2,'lisi',19,1),
(3,'djb',20,2),
(4,'dogfa',40,3),
(5,'oldniu',18,2);
3.删除表
#按道理来说,删除了部门表中的某个部门,员工表的有关联的记录相继删除。
mysql> delete from dep where id=3;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails 
(`db5`.`emp`, CONSTRAINT `fk_name` FOREIGN KEY (`dep_id`) REFERENCES `dep` (`id`))
#但是先删除员工表的记录之后,再删除当前部门就没有任何问题
mysql> delete from emp where dep =3;
Query OK, 1 row affected (0.00 sec)
mysql> select * from emp;
+----+----------+-----+--------+
| id | name     | age | dep_id |
+----+----------+-----+--------+
|  1 | zhangsan |  18 |      1 |
|  2 | lisi     |  18 |      1 |
|  3 | djb      |  20 |      2 |
|  5 | oldniu   |  18 |      2 |
+----+----------+-----+--------+
rows in set (0.00 sec)
mysql> delete from dep where id=3;
Query OK, 1 row affected (0.00 sec)

mysql> select * from dep;
+----+-----------+----------------------+
| id | name      | descripe             |
+----+-----------+----------------------+
|  1 | IT        | IT技术有限部门       |
|  2 | 销售部    | 销售部门             |
+----+-----------+----------------------+
rows in set (0.00 sec)

上面的删除表记录的操作比较繁琐,按道理讲,裁掉一个部门,该部门的员工也会被裁掉。其实呢,在建表的时候还有个很重要的内容,叫同步删除,同步更新

接下来将刚建好的两张表全部删除,先删除关联表(emp),再删除被关联表(dep)

接下来:
重复上面的操作建表
注意:在关联表中加入
on delete cascade #同步删除
on update cascade #同步更新

修改emp表:

create table emp(    
    id int primary key,    
    name varchar(20) not null,
    age int not null,
    dep_id int,
    constraint fk_dep foreign key(dep_id) references dep(id) 
    on delete cascade #同步删除    
    on update cascade #同步更新
);

接下来的操作,就符合我们正常的生活中的情况了。

#再去删被关联表(dep)的记录,关联表(emp)中的记录也跟着删除
mysql> delete from dep where id=3;
Query OK, 1 row affected (0.00 sec)

mysql> select * from dep;
+----+-----------+----------------------+
| id | name      | descripe             |
+----+-----------+----------------------+
|  1 | IT        | IT技术有限部门       |
|  2 | 销售部    | 销售部门             |
+----+-----------+----------------------+
rows in set (0.00 sec)
mysql> select * from emp;
+----+----------+-----+--------+
| id | name     | age | dep_id |
+----+----------+-----+--------+
|  1 | zhangsan |  18 |      1 |
|  2 | lisi     |  19 |      1 |
|  3 | djb      |  20 |      2 |
|  5 | oldniu   |  18 |      2 |
+----+----------+-----+--------+
rows in set (0.00 sec)

#再去更改被关联表(dep)的记录,关联表(emp)中的记录也跟着更改

 mysql> update dep set id=222 where id=2; 
Query OK, 1 row affected (0.02 sec)
Rows matched: 1  Changed: 1  Warnings: 0
# 赶紧去查看一下两张表是否都被删除了,是否都被更改了
mysql> select * from dep;
+-----+-----------+----------------------+
| id  | name      | descripe             |
+-----+-----------+----------------------+
|   1 | IT        | IT技术有限部门       |
| 222 | 销售部    | 销售部门             |
+-----+-----------+----------------------+
rows in set (0.00 sec)
mysql> select * from emp;
+----+----------+-----+--------+
| id | name     | age | dep_id |
+----+----------+-----+--------+
|  1 | zhangsan |  18 |      1 |
|  2 | lisi     |  19 |      1 |
|  3 | djb      |  20 |    222 |
|  5 | oldniu   |  18 |    222 |
+----+----------+-----+--------+
rows in set (0.00 sec)

以上便是常用约束的详细实例介绍,想了解更多相关问题请访问PHP中文网:mysql视频教程

相关专题

更多
php文件怎么打开
php文件怎么打开

打开php文件步骤:1、选择文本编辑器;2、在选择的文本编辑器中,创建一个新的文件,并将其保存为.php文件;3、在创建的PHP文件中,编写PHP代码;4、要在本地计算机上运行PHP文件,需要设置一个服务器环境;5、安装服务器环境后,需要将PHP文件放入服务器目录中;6、一旦将PHP文件放入服务器目录中,就可以通过浏览器来运行它。

1965

2023.09.01

php怎么取出数组的前几个元素
php怎么取出数组的前几个元素

取出php数组的前几个元素的方法有使用array_slice()函数、使用array_splice()函数、使用循环遍历、使用array_slice()函数和array_values()函数等。本专题为大家提供php数组相关的文章、下载、课程内容,供大家免费下载体验。

1292

2023.10.11

php反序列化失败怎么办
php反序列化失败怎么办

php反序列化失败的解决办法检查序列化数据。检查类定义、检查错误日志、更新PHP版本和应用安全措施等。本专题为大家提供php反序列化相关的文章、下载、课程内容,供大家免费下载体验。

1198

2023.10.11

php怎么连接mssql数据库
php怎么连接mssql数据库

连接方法:1、通过mssql_系列函数;2、通过sqlsrv_系列函数;3、通过odbc方式连接;4、通过PDO方式;5、通过COM方式连接。想了解php怎么连接mssql数据库的详细内容,可以访问下面的文章。

948

2023.10.23

php连接mssql数据库的方法
php连接mssql数据库的方法

php连接mssql数据库的方法有使用PHP的MSSQL扩展、使用PDO等。想了解更多php连接mssql数据库相关内容,可以阅读本专题下面的文章。

1400

2023.10.23

html怎么上传
html怎么上传

html通过使用HTML表单、JavaScript和PHP上传。更多关于html的问题详细请看本专题下面的文章。php中文网欢迎大家前来学习。

1229

2023.11.03

PHP出现乱码怎么解决
PHP出现乱码怎么解决

PHP出现乱码可以通过修改PHP文件头部的字符编码设置、检查PHP文件的编码格式、检查数据库连接设置和检查HTML页面的字符编码设置来解决。更多关于php乱码的问题详情请看本专题下面的文章。php中文网欢迎大家前来学习。

1439

2023.11.09

php文件怎么在手机上打开
php文件怎么在手机上打开

php文件在手机上打开需要在手机上搭建一个能够运行php的服务器环境,并将php文件上传到服务器上。再在手机上的浏览器中输入服务器的IP地址或域名,加上php文件的路径,即可打开php文件并查看其内容。更多关于php相关问题,详情请看本专题下面的文章。php中文网欢迎大家前来学习。

1303

2023.11.13

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

7

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
PostgreSQL 教程
PostgreSQL 教程

共48课时 | 6.3万人学习

JavaScript设计模式完整视频教程
JavaScript设计模式完整视频教程

共60课时 | 12.1万人学习

黑马云课堂mongodb实操视频教程
黑马云课堂mongodb实操视频教程

共11课时 | 3.1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号