当前位置:首页 > MySQL教程 > 正文内容

mysql完整性束缚细致引见【MySQL教程】,完整性约束

搜教程4年前 (2019-12-01)MySQL教程193
一、引见

束缚条件与数据范例的宽度一样,都是可选参数

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

主要分为:

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');

团结唯一:

# 建立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)

以上就是经常使用束缚的细致实例引见,想相识更多相干题目请接见ki4网:mysql视频教程

以上就是mysql完整性束缚细致引见的细致内容,更多请关注ki4网别的相干文章!

扫描二维码推送至手机访问。

版权声明:本文由搜教程网发布,如需转载请注明出处。

本文链接:https://www.sojiaocheng.cn/16243.html

标签: 完整性约束
分享给朋友:

“mysql完整性束缚细致引见【MySQL教程】,完整性约束” 的相关文章

MYSQL数据库服务器高iowait怎样优化【MySQL教程】,iowait,MYSQL,服务器

一个数据库服务器高iowait的优化案例 1.开辟反应某一测试环境sql运转迟缓,而在其他测试环境该sql运转很快。两个环境其设置雷同,均只布置了mysql服务器。 2.实行top敕令发明sql运转迟缓的机械上磁盘iowait较sql运转较快的机械凌驾许多。推想这是以致sql运转迟缓的主因,...

mysql5.1 command line client 登录时涌现闪退怎样处理【MySQL教程】,mysql5.1,command,client

由于长时间没有运用mysql command line client。今天在运用时,翻开界面,输入暗码后就涌现了闪退,同时workbench平台也显现不能衔接数据库。起首我照着百度试了一下,觉察在“计算机“-->"治理"(右键)-->“效劳”下,没有找到mysql有关的效劳。 处理办法以...

Mysql删除反复数据保存最小的id【MySQL教程】,Mysql,保留,数据

在网上查找删除反复数据保存id最小的数据,要领以下: DELETE FROM people WHERE peopleName IN ( SELECT peopleName FROM...

数据库查询优化要领【MySQL教程】,数据库,方法,查询

数据库查询优化要领【MySQL教程】,数据库,方法,查询

数据库查询优化 1.运用索引 应只管防止全表扫描,首先应斟酌在 where 及 order by ,groupby 触及的列上竖立索引。 2.优化sql语句 经由过程 explain(查询优化神器)用来检察 SQL 语句的实行效果,能够协助挑选更好的索引和优化查询...

Mysql中的Datetime和Timestamp不同之处【MySQL教程】,Timestamp,Datetime,Mysql

mysql中用于示意时刻的三种范例date, datetime, timestamp (如果算上int的话,四种) 比较轻易殽杂,下面就比较一下这三种范例的异同 相同点 都能够用于示意时刻都呈字符串显现 不同点 1.望文生义,date只示意'YYYY-MM-DD'情势的日期,dateti...

sql中or语法引见【MySQL教程】,介绍,语法

1.mysql中or语法的运用,在mysql语法中or运用注重点。 $sql = 'SELECT * FROM `vvt_spread_doubleegg_exchange_awa...