Mysql完整性約束

1、介紹

約束條件與數據類型的寬度同樣,都是可選參數mysql

做用:用於保證數據的完整性和一致性sql

主要分爲:session

PRIMARY KEY (PK)    #標識該字段爲該表的主鍵,能夠惟一的標識記錄
FOREIGN KEY (FK)    #標識該字段爲該表的外鍵
NOT NULL    #標識該字段不能爲空
UNIQUE KEY (UK)    #標識該字段的值是惟一的
AUTO_INCREMENT    #標識該字段的值自動增加(整數類型,並且爲主鍵)
DEFAULT    #爲該字段設置默認值

UNSIGNED #無符號
ZEROFILL #使用0填充

說明:ide

#1. 是否容許爲空,默認NULL,可設置NOT NULL,字段不容許爲空,必須賦值
#2. 字段是否有默認值,缺省的默認值是NULL,若是插入記錄時不給字段賦值,此字段使用默認值
sex enum('male','female') not null default 'male'

#必須爲正值(無符號) 不容許爲空 默認是20
age int unsigned NOT NULL default 20 
# 3. 是不是key
主鍵 primary key
外鍵 foreign key
索引 (index,unique...)

2、not null 與default

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

默認值,建立列時能夠指定默認值,當插入數據時若是未主動設置,則自動添加默認值spa

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

); 

驗證1: 翻譯

mysql> create table t11(id int);# id字段默承認覺得空
Query OK, 0 rows affected (0.05 sec)

mysql> desc t11;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | YES   |          | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.03 sec)
mysql> insert into t11 values(); #給t11表插一個空的值
Query OK, 1 row affected (0.00 sec)

#查詢結果以下
mysql> select * from t11;
+------+
| id   |
+------+
| NULL |
+------+
1 row in set (0.00 sec)
默認值能夠爲空

驗證2:3d

mysql> create table t12(id int not null);#設置字段id不爲空
Query OK, 0 rows affected (0.03 sec)

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

mysql> insert into t12 values();#不能插入空
ERROR 1364 (HY000): Field 'id' doesn't have a default value
設置not null,插入值時不能爲空

驗證3:code

# 第一種狀況
mysql> create table t13(id int default 1);
Query OK, 0 rows affected (0.03 sec)

mysql> desc t13;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | YES  |           | 1              |              |
+-------+---------+------+-----+---------+-------+
1 row in set (0.01 sec)

mysql> insert into t13 values();
Query OK, 1 row affected (0.00 sec)

mysql> select * from t13;
+------+
| id   |
+------+
|    1  |
+------+
1 row in set (0.00 sec)


# 第二種狀況
mysql> create table t14(id int not null default 2);
Query OK, 0 rows affected (0.02 sec)

mysql> desc t14;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO      |         | 2               |             |
+-------+---------+------+-----+---------+-------+
1 row in set (0.01 sec)

mysql> select * from t14;
+----+
| id |
+----+
|  2 |
+----+
1 row in set (0.00 sec)
設置id字段有默認值後,則不管id字段是null仍是not null,均可以插入空,插入空默認填入default指定的默認值

 小練習:blog

建立學生表student2,設置每一個字段的約束條件。

mysql> create table student2(
    -> id int not null,
    -> name varchar(50) not null,
    -> age int(3) unsigned not null default 18,
    -> sex enum('male','female') default 'male',
    -> fav set('smoke','drink','tangtou') default 'drink,tangtou'
    -> );
Query OK, 0 rows affected (0.01 sec)

# 只插入了not null約束條件的字段對應的值
mysql> insert into student2(id,name) values(1,'mjj');
Query OK, 1 row affected (0.00 sec)

# 查詢結果以下
mysql> select * from student2;
+----+------+-----+------+---------------+
| id | name | age | sex  | fav           |
+----+------+-----+------+---------------+
|  1 | mjj  |  18 | male | drink,tangtou |
+----+------+-----+------+---------------+
1 row in set (0.00 sec)

三、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: 0

mysql> 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'

4.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);
驗證複合主鍵的使用

 應用舉例:好比'選課'系統(學生號,課程號,分數),每一個學生能夠選修多門課程,每門課程能夠有多名學生選修。

5.auto_increment

約束:約束的字段爲自動增加,約束的字段必須同時被key約束

 

(重點)驗證:

# 建立student
create 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    |                |
+-------+-----------------------+------+-----+---------+----------------+
3 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: 0

mysql> select * from student;
+----+--------+------+
| id | name   | sex  |
+----+--------+------+
|  1 | 老白   | male |
|  2 | 小白   | male |
+----+--------+------+
2 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 |
+----+--------+--------+
4 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   |
+----+--------+--------+
5 rows in set (0.00 sec)
也能夠指定id

 

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 |
+----+------+------+
1 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 |
+----+---------+------+
1 row in set (0.00 sec)

mysql>
對於自增的字段,在用delete刪除後,再插入值,該字段仍按照刪除前的位置繼續增加

 

瞭解:

查看可用的 開頭auto_inc的詞
mysql> show variables like 'auto_inc%';
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| auto_increment_increment | 1     |
| auto_increment_offset    | 1     |
+--------------------------+-------+
2 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     |
+--------------------------+-------+
2 rows in set (0.00 sec)

#由於以前有一條記錄id=1
mysql> select * from student;
+----+---------+------+
| id | name    | sex  |
+----+---------+------+
|  1 | xiaobai | male |
+----+---------+------+
1 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

清空表區分delete和truncate的區別:

delete from t1; #若是有自增id,新增的數據,仍然是以刪除前的最後同樣做爲起始。

truncate table t1;數據量大,刪除速度比上一條快,且直接從零開始。

6.foreign key

一 快速理解foreign key

以前建立表的時候都是在一張表中添加記錄,好比以下表:

 

公司有3個部門,可是有1個億的員工,那意味着部門這個字段須要重複存儲,部門名字越長,越浪費。

這個時候,

解決方法:

咱們徹底能夠定義一個部門表

而後讓員工信息表關聯該表,如何關聯,即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 =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)
View Code

上面的刪除表記錄的操做比較繁瑣,按道理講,裁掉一個部門,該部門的員工也會被裁掉。其實呢,在建表的時候還有個很重要的內容,叫同步刪除,同步更新

接下來將剛建好的兩張表所有刪除,先刪除關聯表(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 | 銷售部    | 銷售部門             |
+----+-----------+----------------------+
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)
相關文章
相關標籤/搜索