1.介紹:
約束條件與資料型別的寬度一樣,都是可選引數
作用:用於保證資料的完整性和一致性
主要分為:
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' #必須為正值(無符號) 不允許為空 預設是20 age int unsigned NOT NULL default 20 # 3. 是否是key 主鍵 primary key 外來鍵 foreign key 索引 (index,unique...)
2.not null 和default
是否可空,null表示空,非字串
not null - 不可空
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 | | +-------+---------+------+-----+---------+-------+ 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 | +------+ row in set (0.00 sec) 預設值可以為空
在mysql5.7.21版本中約束int型別不為空的時候,插入空值不會報錯,顯示0.
驗證2
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 | | +-------+---------+------+-----+---------+-------+ 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
# 第一種情況 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 | | +-------+---------+------+-----+---------+-------+ 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 | +------+ 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 | | +-------+---------+------+-----+---------+-------+ row in set (0.01 sec) mysql> select * from t14; +----+ | id | +----+ | 2 | +----+ row in set (0.00 sec) 設定id欄位有預設值後,則無論id欄位是null還是not null,都可以插入空,插入空預設填入default指定的預設值
練習:建立學生表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 | +----+------+-----+------+---------------+ row in set (0.00 sec)
3.unique:單列唯一
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 | +----+------+-----+------+---------------+ row 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 | | +-------+----------+------+-----+---------+-------+ 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 | +------+---------------+------+ 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
一個表中可以:
單列做主鍵
多列做主鍵(複合主鍵)
約束:等價於 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 | | +-------+----------+------+-----+---------+-------+ 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 | | +-------+-----------------------+------+-----+---------+----------------+ 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 | +----+--------+------+ 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) 也可以指定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 | +----+------+------+ 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> 對於自增的欄位,在用delete刪除後,再插入值,該欄位仍按照刪除前的位置繼續增長
瞭解:
檢視可用的 開頭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
清空表區分delete和truncate的區別:
delete from t1; #如果有自增id,新增的資料,仍然是以刪除前的最後一樣作為起始。
truncate table t1;資料量大,刪除速度比上一條快,且直接從零開始。
6.foregin 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 | +----+----------+-----+--------+ 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 | egon | 20 | 2 | | 5 | alex | 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 | egon | 20 | 222 | | 5 | alex | 18 | 222 | +----+----------+-----+--------+ rows in set (0.00 sec)