侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

mysql完整性约束实例详解

数据库  /  管理员 发布于 6年前   195

本文实例讲述了mysql完整性约束。分享给大家供大家参考,具体如下:

主要内容

  • not null 与 default
  • unique
  • primary
  • auto_increment
  • foreign key

约束条件作用:用于保证数据的完整性和一致性

主要分为

PRIMARY KEY (PK)    #标识该字段为该表的主键,可以唯一的标识记录
FOREIGN KEY (FK)    #标识该字段为该表的外键
NOT NULL    #标识该字段不能为空
UNIQUE KEY (UK)    #标识该字段的值是唯一的,
AUTO_INCREMENT    #标识该字段的值自动增长(整数类型,而且为主键)
DEFAULT    #为该字段设置默认值
UNSIGNED #无符号
ZEROFILL #使用0填充

unique

在mysql中称为单列唯一

#例子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');

联合唯一:只要两列记录,有一列不同,既符合联合唯一的约束

# 创建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: 0mysql> 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'

auto_increment

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

不指定id,则自动增长

# 创建studentcreate table student(id int primary key auto_increment,name varchar(20),sex enum('male','female') default 'male');mysql> desc student;+-------+-----------------------+------+-----+---------+----------------+| Field | Type         | Null | Key | Default | Extra     |+-------+-----------------------+------+-----+---------+----------------+| id  | int(11)        | NO  | PRI | NULL  | auto_increment || name | varchar(20)      | YES |   | NULL  |        || sex  | enum('male','female') | YES |   | male  |        |+-------+-----------------------+------+-----+---------+----------------+rows in set (0.17 sec)#插入记录mysql> insert into student(name) values ('老白'),('小白');Query OK, 2 rows affected (0.01 sec)Records: 2 Duplicates: 0 Warnings: 0mysql> select * from student;+----+--------+------+| id | name  | sex |+----+--------+------+| 1 | 老白  | male || 2 | 小白  | male |+----+--------+------+rows in set (0.00 sec)

指定id的情况

mysql> insert into student values(4,'asb','female');Query OK, 1 row affected (0.00 sec)mysql> insert into student values(7,'wsb','female');Query OK, 1 row affected (0.01 sec)mysql> select * from student;+----+--------+--------+| id | name  | sex  |+----+--------+--------+| 1 | 老白  | male  || 2 | 小白  | male  || 4 | asb  | female || 7 | wsb  | female |+----+--------+--------+rows in set (0.00 sec)# 再次插入一条不指定id的记录,会在之前的最后一条记录继续增长mysql> insert into student(name) values ('大白');Query OK, 1 row affected (0.00 sec)mysql> select * from student;+----+--------+--------+| id | name  | sex  |+----+--------+--------+| 1 | 老白  | male  || 2 | 小白  | male  || 4 | asb  | female || 7 | wsb  | female || 8 | 大白  | male  |+----+--------+--------+rows in set (0.00 sec)

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

mysql> delete from student;Query OK, 5 rows affected (0.00 sec)mysql> select * from student;Empty set (0.00 sec)mysql> select * from student;Empty set (0.00 sec)mysql> insert into student(name) values('ysb');Query OK, 1 row affected (0.01 sec)mysql> select * from student;+----+------+------+| id | name | sex |+----+------+------+| 9 | ysb | male |+----+------+------+row in set (0.00 sec)#应该用truncate清空表,比起delete一条一条地删除记录,truncate是直接清空表,在删除大表时用它mysql> truncate student;Query OK, 0 rows affected (0.03 sec)mysql> insert into student(name) values('xiaobai');Query OK, 1 row affected (0.00 sec)mysql> select * from student;+----+---------+------+| id | name  | sex |+----+---------+------+| 1 | xiaobai | male |+----+---------+------+row in set (0.00 sec)mysql>auto_increment_increment和 auto_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=1mysql> select * from student;+----+---------+------+| id | name  | sex |+----+---------+------+| 1 | xiaobai | male |+----+---------+------+row in set (0.00 sec)# 下次插入的时候,从起始位置3开始,每次插入记录id+5mysql> insert into student(name) values('ma1'),('ma2'),('ma3');Query OK, 3 rows affected (0.00 sec)Records: 3 Duplicates: 0 Warnings: 0mysql> select * from student;+----+---------+------+| id | name  | sex |+----+---------+------+| 1 | xiaobai | male || 3 | ma1   | male || 8 | ma2   | male || 13 | ma3   | male |+----+---------+------+

清空表区分delete和truncate的区别:

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

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

foreign key

理解foreign key

 

如上图如果一个公司有很多员工,每个员工都对应一个部门,在填表的时候就会重复写这些部门,太冗余了

我们可以将它们分离

 

此时有两张表,一张是employee表,简称emp表(关联表,也就从表)。一张是department表,简称dep表(被关联表,也叫主表)。

#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,'egon',20,2),(4,'yuanhao',40,3),(5,'alex',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_id =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 | egon   | 20 |   2 || 5 | alex   | 18 |   2 |+----+----------+-----+--------+4 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 | 销售部  | 销售部门       |+----+-----------+----------------------+2 rows in set (0.00 sec)

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

on delete cascade #同步删除
on update cascade #同步更新

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 | 销售部  | 销售部门       |+----+-----------+----------------------+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 | egon   | 20 |   2 || 5 | alex   | 18 |   2 |+----+----------+-----+--------+4 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 | 销售部  | 销售部门       |+-----+-----------+----------------------+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 | egon   | 20 |  222 || 5 | alex   | 18 |  222 |+----+----------+-----+--------+4 rows in set (0.00 sec)

更多关于MySQL相关内容感兴趣的读者可查看本站专题:《MySQL查询技巧大全》、《MySQL常用函数大汇总》、《MySQL日志操作技巧大全》、《MySQL事务操作技巧汇总》、《MySQL存储过程技巧大全》及《MySQL数据库锁相关技巧汇总》

希望本文所述对大家MySQL数据库计有所帮助。


  • 上一条:
    mysql中的sql_mode模式实例详解
    下一条:
    mysql外键的三种关系实例详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 分库分表的目的、优缺点及具体实现方式介绍(0个评论)
    • DevDB - 在 VS 代码中直接访问数据库(0个评论)
    • 在ubuntu系统中实现mysql数据存储目录迁移流程步骤(0个评论)
    • 在mysql中使用存储过程批量新增测试数据流程步骤(0个评论)
    • php+mysql数据库批量根据条件快速更新、连表更新sql实现(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-06
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-01
    • 2018-05
    • 2018-10
    • 2018-11
    • 2020-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2021-02
    • 2021-04
    • 2021-07
    • 2021-08
    • 2021-11
    • 2021-12
    • 2022-02
    • 2022-03
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-07
    • 2023-08
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客