約束條件與數據類型的寬度同樣,都是可選參數mysql
做用:用於保證數據的完整性和一致性
主要分爲:nginx
PRIMARY KEY (PK) 標識該字段爲該表的主鍵,能夠惟一的標識記錄 FOREIGN KEY (FK) 標識該字段爲該表的外鍵 NOT NULL 標識該字段不能爲空 UNIQUE KEY (UK) 標識該字段的值是惟一的 AUTO_INCREMENT 標識該字段的值自動增加(整數類型,並且爲主鍵) DEFAULT 爲該字段設置默認值 UNSIGNED 無符號 ZEROFILL 使用0填充
說明:sql
1. 是否容許爲空,默認NULL,可設置NOT NULL,字段不容許爲空,必須賦值
session
2. 字段是否有默認值,缺省的默認值是NULL,若是插入記錄時不給字段賦值,此字段使用默認值
cors
sex enum('male','female') not null default 'male'
ide
age int unsigned NOT NULL default 20 必須爲正值(無符號) 不容許爲空 默認是20
sqlserver
3. 是不是key
編碼
主鍵 primary key
url
外鍵 foreign key
spa
索引 (index,unique...)
是否可空,null表示空,非字符串
not null - 不可空
null - 可空
默認值,建立列時能夠指定默認值,當插入數據時若是未主動設置,則自動添加默認值
create table tb1(
nid int not null defalut 2,
num int not null
)
==================not null==================== mysql> create table t1(id int); #id字段默承認以插入空 mysql> desc t1; +-------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | +-------+---------+------+-----+---------+-------+ mysql> insert into t1 values(); #能夠插入空 mysql> create table t2(id int not null); #設置字段id不爲空 mysql> desc t2; +-------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+-------+ | id | int(11) | NO | | NULL | | +-------+---------+------+-----+---------+-------+ mysql> insert into t2 values(); #不能插入空 ERROR 1364 (HY000): Field 'id' doesn't have a default value ==================default==================== #設置id字段有默認值後,則不管id字段是null仍是not null,均可以插入空,插入空默認填入default指定的默認值 mysql> create table t3(id int default 1); mysql> alter table t3 modify id int not null default 1;
mysql> create table t15( -> id int(11) unsigned zerofill # id爲字段,必須爲字段指定數據類型(int);在數據條件下添加約束條件:unsigned限制id只 能傳入無符號 -> ); Query OK, 0 rows affected (0.01 sec) mysql> desc t15 -> ; +-------+---------------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+---------------------------+------+-----+---------+-------+ | id | int(11) unsigned zerofill | YES | | NULL | | +-------+---------------------------+------+-----+---------+-------+ 1 row in set (0.00 sec) # not null 不能爲空,default設置默認值 mysql> create table t16( -> id int, -> name char(6), -> sex enum('male', 'female') not null default 'male' # 不能爲空,傳空就用默認值'male' -> ); Query OK, 0 rows affected (0.01 sec) mysql> desc t16; +-------+-----------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-----------------------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | | name | char(6) | YES | | NULL | | | sex | enum('male','female') | NO | | male | | +-------+-----------------------+------+-----+---------+-------+ 3 rows in set (0.01 sec) mysql> insert into t16(id,name) values(1,'egon'); Query OK, 1 row affected (0.00 sec) mysql> select * from t16; +------+--------+------+ | id | name | sex | +------+--------+------+ | 1 | egon | male | +------+--------+------+ 1 row in set (0.00 sec)
unique key指的就是限制字段傳入的值是惟一的,不能重複的。
# 建立部門表,且部門名稱不設置unique,所以能夠建立多個同名部門名稱,這明顯不合理 mysql> create table department( -> id int, -> name char(10) -> ); Query OK, 0 rows affected (0.01 sec) mysql> desc department; +-------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | | name | char(10) | YES | | NULL | | +-------+----------+------+-----+---------+-------+ 2 rows in set (0.00 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) # 設置惟一約束unique # 方式一: mysql> drop table department; Query OK, 0 rows affected (0.01 sec) mysql> create table department( -> id int, -> name char(10) unique -> ); Query OK, 0 rows affected (0.01 sec) mysql> desc department; +-------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | | name | char(10) | YES | UNI | NULL | | +-------+----------+------+-----+---------+-------+ 2 rows in set (0.00 sec) mysql> insert into department values -> (1, 'IT'), -> (2, 'IT'); ERROR 1062 (23000): Duplicate entry 'IT ' for key 'name' # 方式二: mysql> drop table department; Query OK, 0 rows affected (0.01 sec) mysql> create table department( -> id int, -> name char(10), -> unique(id), -> unique(name) -> ); Query OK, 0 rows affected (0.01 sec) mysql> desc department; +-------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+-------+ | id | int(11) | YES | UNI | NULL | | | name | char(10) | YES | UNI | NULL | | +-------+----------+------+-----+---------+-------+ 2 rows in set (0.00 sec) mysql> insert into department values -> (1,'IT'), -> (2,'IT'); ERROR 1062 (23000): Duplicate entry 'IT ' for key 'name' mysql> insert into department values (1,'IT'), (2,'Sale'); Query OK, 2 rows affected (0.00 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> selcet * from department; ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'selcet * from department' at line 1 mysql> select * from department; +------+------------+ | id | name | +------+------------+ | 1 | IT | | 2 | Sale | +------+------------+ 2 rows in set (0.00 sec)
mysql> create table services( -> id int, -> ip char(15), -> port int, -> unique(id), # 單列惟一 -> unique(ip,port) # 聯合惟一:ip+port惟一 -> ); Query OK, 0 rows affected (0.01 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.00 sec) mysql> insert into services values -> (1,'192.168.1.101',80), -> (2,'192.168.1.101',88), -> (3,'192.168.1.103',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.1.101 | 80 | | 2 | 192.168.1.101 | 88 | | 3 | 192.168.1.103 | 80 | +------+-----------------+------+ 3 rows in set (0.00 sec) mysql> insert into services values (4,'192.168.1.101',80); ERROR 1062 (23000): Duplicate entry '192.168.1.101 -80' for key 'ip'
從約束角度看primary key字段的值不爲空且惟一(not null unique)。
那直接使用not null+unique不就能夠了嗎,要primary key幹什麼?
主鍵primary key是innodb存儲引擎組織數據的依據(innodb稱之爲索引組織表,對於innodb存儲引擎一張表中必須有且只有一個主鍵)。
一個表中能夠:單列作主鍵、多列作主鍵(複合主鍵)
============單列作主鍵=============== #方法一:not null+unique mysql> create table department( -> id int not null unique, # 主鍵,一般設置id爲主鍵 -> name varchar(20) not null unique, -> comment varchar(100) -> ); Query OK, 0 rows affected (0.01 sec) mysql> desc department; +---------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+--------------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | varchar(20) | NO | UNI | NULL | | | comment | varchar(100) | YES | | NULL | | +---------+--------------+------+-----+---------+-------+ 3 rows in set (0.00 sec) #方法二:在某一個字段後用primary key mysql> create table department2( -> id int primary key, # 主鍵 -> name varchar(20), -> comment varchar(100) -> ); Query OK, 0 rows affected (0.01 sec) mysql> desc department2; +---------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+--------------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | varchar(20) | YES | | NULL | | | comment | varchar(100) | YES | | NULL | | +---------+--------------+------+-----+---------+-------+ 3 rows in set (0.00 sec) # 方法三:在全部字段後單獨定義primary key mysql> create table department3( -> id int, -> name varchar(20), -> comment varchar(100), -> constraint pk_name primary key(id) #建立主鍵並命名爲pk_name -> ); Query OK, 0 rows affected (0.02 sec) mysql> desc department3; +---------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+--------------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | varchar(20) | YES | | NULL | | | comment | varchar(100) | YES | | NULL | | +---------+--------------+------+-----+---------+-------+ 3 rows in set (0.01 sec)
==================多列作主鍵================ mysql> create table service( -> ip varchar(15), -> port char(5), -> service_name varchar(10) not null, -> primary key(ip,port) # 多列主鍵 -> ); Query OK, 0 rows affected (0.01 sec) mysql> desc service; +--------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------+-------------+------+-----+---------+-------+ | ip | varchar(15) | NO | PRI | NULL | | | port | char(5) | NO | PRI | NULL | | | service_name | varchar(10) | NO | | NULL | | +--------------+-------------+------+-----+---------+-------+ 3 rows in set (0.00 sec) mysql> insert into service values -> ('172.16.45.10', '3306', 'mysqld'), -> ('172.16.45.11', '3306', 'mariadb') -> ; Query OK, 2 rows affected (0.00 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> select * from service; +--------------+-------+--------------+ | ip | port | service_name | +--------------+-------+--------------+ | 172.16.45.10 | 3306 | mysqld | | 172.16.45.11 | 3306 | mariadb | +--------------+-------+--------------+ 2 rows in set (0.00 sec) mysql> insert into service values ('172.16.45.10', '3306', 'nginx'); ERROR 1062 (23000): Duplicate entry '172.16.45.10-3306 ' for key 'PRIMARY'
總結:只要用的表類型是innodb(最經常使用),就應該爲表指定一個主鍵,且通常都是指定爲id字段。
約束字段爲自動增加,被約束的字段必須同時被key約束。
mysql> create table t19( -> id int auto_increment -> ); ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key # 自增加必須是一個key,如今學到的key分爲兩種:unique\primary mysql> create table t19( -> id int unique key auto_increment -> ); Query OK, 0 rows affected (0.02 sec) mysql> desc t19; +-------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | +-------+---------+------+-----+---------+----------------+ 1 row in set (0.00 sec)
#不指定id,則自動增加 mysql> create table student( -> id int primary key auto_increment, -> name varchar(20), -> sex enum('male','female') default 'male' -> ); Query OK, 0 rows affected (0.01 sec) 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.00 sec) mysql> insert into student(name) values -> ('hqs') -> ,('aelx'), -> ('egon') -> ; Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from student; +----+------+------+ | id | name | sex | +----+------+------+ | 1 | hqs | male | | 2 | aelx | male | | 3 | egon | male | +----+------+------+ 3 rows in set (0.00 sec) # 指定id插入 mysql> insert into student values -> (5, 'asb', 'female'); Query OK, 1 row affected (0.01 sec) mysql> insert into student values -> (12, 'zr', 'female'); Query OK, 1 row affected (0.00 sec) mysql> select * from student; +----+------+--------+ | id | name | sex | +----+------+--------+ | 1 | hqs | male | | 2 | aelx | male | | 3 | egon | male | | 5 | asb | female | | 12 | zr | female | +----+------+--------+ 5 rows in set (0.00 sec)
注意:插入指定id的記錄後,再插入不指定id記錄時,新記錄按照最後一條記錄的id編碼繼續日後編排。
mysql> show variables like 'auto_inc%'; # %表明任意個數任意字符 +--------------------------+-------+ | Variable_name | Value | +--------------------------+-------+ | auto_increment_increment | 1 | # 查到步長,且默認爲1 | auto_increment_offset | 1 | # 查到起始偏移量。且默認也爲1 +--------------------------+-------+ 2 rows in set (0.02 sec)
設置步長
set session auto_increment_increment=5; # session關鍵詞,說明這個步長修改是會話級別的,只在本次連接有效
set global auto_increment_increment=5; # 修改全局級別的步長,全部會話須要退出後從新鏈接才生效
#設置步長 sqlserver:自增步長 基於表級別 create table t1( id int。。。 )engine=innodb,auto_increment=2 步長=2 default charset=utf8 mysql自增的步長: show session variables like 'auto_inc%'; #基於會話級別 set session auth_increment_increment=2 #修改會話級別的步長 #基於全局級別的 set global auth_increment_increment=2 #修改全局級別的步長(全部會話都生效) #!!!注意了注意了注意了!!! 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的值會被忽略 好比:設置auto_increment_offset=3,auto_increment_increment=2
設置起始偏移量
set global auto_increment_offset=6; # 設置失效,注意:起始偏移量必須小於等於步長
#在建立完表後,修改自增字段的起始值 mysql> create table student( -> id int primary key auto_increment, -> name varchar(20), -> sex enum('male','female') default 'male' -> ); mysql> alter table student auto_increment=3; mysql> show create table student; ....... ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 mysql> insert into student(name) values('egon'); Query OK, 1 row affected (0.01 sec) mysql> select * from student; +----+------+------+ | id | name | sex | +----+------+------+ | 3 | egon | male | +----+------+------+ row in set (0.00 sec) mysql> show create table student; ....... ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 #也能夠建立表時指定auto_increment的初始值,注意初始值的設置爲表選項,應該放到括號外 create table student( id int primary key auto_increment, name varchar(20), sex enum('male','female') default 'male' )auto_increment=3;
mysql> show variables like 'auto_incre%'; +--------------------------+-------+ | Variable_name | Value | +--------------------------+-------+ | auto_increment_increment | 1 | | auto_increment_offset | 1 | +--------------------------+-------+ 2 rows in set (0.01 sec) mysql> set global auto_increment_increment=5; # 修改步長 Query OK, 0 rows affected (0.00 sec) mysql> set global auto_increment_offset=3; # 修改起始便宜量 Query OK, 0 rows affected (0.00 sec) mysql> exit # 全局修改後須要退出當前會話 Bye sh-3.2# mysql -uroot -p1234 mysql> show variables like 'auto_in%'; +--------------------------+-------+ | Variable_name | Value | +--------------------------+-------+ | auto_increment_increment | 5 | | auto_increment_offset | 3 | +--------------------------+-------+ 2 rows in set (0.00 sec) mysql> use db4 Database changed mysql> create table student1( -> id int primary key auto_increment, -> name varchar(20), -> sex enum('male', 'female') default 'male' -> ); Query OK, 0 rows affected (0.01 sec) mysql> insert into student1 -> \c mysql> insert into student1(name) values -> ('egon'), -> ('alex'), -> ('hqs'); Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from student1; +----+------+------+ | id | name | sex | +----+------+------+ | 3 | egon | male | | 8 | alex | male | | 13 | hqs | male | +----+------+------+ 3 rows in set (0.00 sec)
方法一:delete from 表名; ——存在的問題:對於自增的字段,在用delete刪除後,再插入值,該字段仍按照刪除前的位置繼續增加
。
delete更適用於局部記錄的刪除:delete from t20 where id=3;
方法二:truncate 表名; ——truncate清空表,不一樣於delete一條一條刪除,是直接清空表,刪除大表時推薦使用。
mysql> set global auto_increment_increment=1; Query OK, 0 rows affected (0.00 sec) mysql> set global auto_increment_offset=1; Query OK, 0 rows affected (0.00 sec) mysql> exit sh-3.2# mysql -uroot -p1234 # 從新登陸,使得新的步長和起始偏移量生效 mysql> select * from student1; +----+------+------+ | id | name | sex | +----+------+------+ | 3 | egon | male | | 8 | alex | male | | 13 | hqs | male | +----+------+------+ 3 rows in set (0.00 sec) mysql> delete from student1; Query OK, 3 rows affected (0.01 sec) mysql> select * from student1; Empty set (0.00 sec) mysql> insert into student1(name) values -> ('asd'); Query OK, 1 row affected (0.00 sec) mysql> select * from student1; +----+------+------+ | id | name | sex | +----+------+------+ | 18 | asd | male | +----+------+------+ 1 row in set (0.00 sec) mysql> show create table student1; +----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | student1 | CREATE TABLE `student1` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) DEFAULT NULL, `sex` enum('male','female') DEFAULT 'male', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 | # 能夠看到偏移量仍是根據以前的id順延 +----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) # 應該用truncate清空表,比起delete一條一條地刪除記錄,truncate是直接清空表,在刪除大表時用它 mysql> truncate student1; Query OK, 0 rows affected (0.02 sec) mysql> show create table student1; +----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | student1 | CREATE TABLE `student1` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) DEFAULT NULL, `sex` enum('male','female') DEFAULT 'male', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | +----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.01 sec) mysql> insert into student1(name) values ('egon'), ('alex'); Query OK, 2 rows affected (0.00 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> select * from student1; +----+------+------+ | id | name | sex | +----+------+------+ | 1 | egon | male | # 能夠看到已經不依照創表前設置的步長和起始偏移量,按照系統當前的設置執行 | 2 | alex | male | +----+------+------+ 2 rows in set (0.00 sec)
foreign key:用來創建表之間的關係。
以一個公司的員工信息表爲例,員工會有id,name,sex,department,comment等字段。可是這樣存儲會在部門和部門描述上有大量字段重複存儲,既浪費空間又不利於後期的維護管理(部門調整或部門更名等)。所以能夠把部門和部門相關信息分拆出來,做爲部門表。此時部門和員工信息表分開,二者之間徹底獨立。須要用外鍵實現兩張表關聯。
# 1、創建表關係 # 建立失敗,由於須要先建立被關聯的表 mysql> create table emp( ->id int primary key, ->name char(10), ->sex enum('male', 'female'), ->dep_id int, ->foreign key(dep_id) references dep(id) ->); ERROR 1215 (HY000): Cannot add foreign key constraint # 先建被關聯的表,並保證被關聯的字段惟一 mysql> create table dep( -> id int primary key, # 或者使用unique,必須保證要關聯的字段是唯一的,才能建立關聯表 -> name char(16), -> comment char(50) -> ); Query OK, 0 rows affected (0.01 sec) mysql> desc dep; +---------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+----------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | char(16) | YES | | NULL | | | comment | char(50) | YES | | NULL | | +---------+----------+------+-----+---------+-------+ 3 rows in set (0.00 sec) # 再建關聯的表 mysql> create table emp( -> id int primary key, -> name char(10), -> sex enum('male', 'female'), -> dep_id int, -> foreign key(dep_id) references dep(id) -> ); Query OK, 0 rows affected (0.01 sec) mysql> desc emp; +--------+-----------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-----------------------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | char(10) | YES | | NULL | | | sex | enum('male','female') | YES | | NULL | | | dep_id | int(11) | YES | MUL | NULL | | +--------+-----------------------+------+-----+---------+-------+ 4 rows in set (0.00 sec) # 2、插入數據 # 直接往員工表插入數據,沒法插入記錄,由於dep_id不能隨便寫入,必須是被關聯內已經具有的數值 mysql> insert into emp values -> (1, 'egon', 'male', '1'); ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`db1`.`emp`, CONSTRAINT `emp_ibfk_1` FOREIGN KEY (`dep_id`) REFERENCES `dep` (`id`)) # 先往被關聯表(dep)插入記錄 mysql> insert into dep values -> (1,'IT','技術能力有限部門'), -> (2,'銷售','銷售能力有限部門'), -> (3,'財務','花錢特別多部門'); Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from dep; +----+--------+--------------------------+ | id | name | comment | +----+--------+--------------------------+ | 1 | IT | 技術能力有限部門 | | 2 | 銷售 | 銷售能力有限部門 | | 3 | 財務 | 花錢特別多部門 | +----+--------+--------------------------+ 3 rows in set (0.00 sec) # 再往關聯表插入記錄 mysql> insert into emp values -> (1, 'egon', 'male', 1), -> (2, 'alex', 'male', 1), -> (3, 'wupeiqi', 'male', 2), -> (4, 'yuanhao', 'male', 3), -> (5, 'jinxin', 'male',2); Query OK, 5 rows affected (0.00 sec) Records: 5 Duplicates: 0 Warnings: 0 mysql> select * from emp; +----+---------+------+--------+ | id | name | sex | dep_id | +----+---------+------+--------+ | 1 | egon | male | 1 | | 2 | alex | male | 1 | | 3 | wupeiqi | male | 2 | | 4 | yuanhao | male | 3 | | 5 | jinxin | male | 2 | +----+---------+------+--------+ 5 rows in set (0.00 sec) # 3、刪除數據 # 要刪除某個部分,須要先刪除子表對應的記錄 mysql> delete from emp where dep_id=1; Query OK, 2 rows affected (0.01 sec) mysql> select * from emp; +----+---------+------+--------+ | id | name | sex | dep_id | +----+---------+------+--------+ | 3 | wupeiqi | male | 2 | | 4 | yuanhao | male | 3 | | 5 | jinxin | male | 2 | +----+---------+------+--------+ 3 rows in set (0.00 sec) mysql> delete from dep where id=1; Query OK, 1 row affected (0.00 sec) mysql> select * from dep; +----+--------+--------------------------+ | id | name | comment | +----+--------+--------------------------+ | 2 | 銷售 | 銷售能力有限部門 | | 3 | 財務 | 花錢特別多部門 | +----+--------+--------------------------+ 2 rows in set (0.00 sec) # 直線先刪除父表直接報錯 mysql> delete from dep where id=3; ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`db1`.`emp`, CONSTRAINT `emp_ibfk_1` FOREIGN KEY (`dep_id`) REFERENCES `dep` (`id`))
上面這種關聯關係雖然創建了,可是數據的維護管理其實仍是很是繁複。要實現刪除(更新)父表,子表對應記錄也自動刪除(更新),須要在建立關聯子表的時候,設置同步刪除,同步更新。
create table emp( id int primary key, name char(10), sex enum('male', 'female'), dep_id int, foreign key(dep_id) references dep(id) on delete cascade # 同步刪除 on update cascade # 同步更新 );
# 刪除全部表 mysql> drop table dep; ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails mysql> drop table emp; Query OK, 0 rows affected (0.01 sec) mysql> drop table dep; Query OK, 0 rows affected (0.00 sec) # 建立被關聯的表,且被關聯的字段惟一 mysql> create table dep( -> id int primary key, -> name char(16), -> comment char(50) -> ); Query OK, 0 rows affected (0.01 sec) # 再建立關聯的表 mysql> create table emp( -> id int primary key, -> name char(10), -> sex enum('male', 'female'), -> dep_id int, -> foreign key(dep_id) references dep(id) -> on delete cascade -> on update cascade -> ); Query OK, 0 rows affected (0.01 sec) # 插入數據 mysql> insert into dep values -> (1,'IT','技術能力有限部門'), -> (2,'銷售','銷售能力有限部門'), -> (3,'財務','花錢特別多部門'); Query OK, 3 rows affected (0.01 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> insert into emp values -> (1,'egon','male',1), -> (2,'alex','male',1), -> (3,'wupeiqi','female',2), -> (4,'yuanhao','male',3), -> (5,'jinxin','male',2); Query OK, 5 rows affected (0.01 sec) Records: 5 Duplicates: 0 Warnings: 0 mysql> select * from dep; +----+--------+--------------------------+ | id | name | comment | +----+--------+--------------------------+ | 1 | IT | 技術能力有限部門 | | 2 | 銷售 | 銷售能力有限部門 | | 3 | 財務 | 花錢特別多部門 | +----+--------+--------------------------+ 3 rows in set (0.00 sec) mysql> select * from emp; +----+---------+--------+--------+ | id | name | sex | dep_id | +----+---------+--------+--------+ | 1 | egon | male | 1 | | 2 | alex | male | 1 | | 3 | wupeiqi | female | 2 | | 4 | yuanhao | male | 3 | | 5 | jinxin | male | 2 | +----+---------+--------+--------+ 5 rows in set (0.00 sec) # 刪除父表,子表emp中對應記錄跟着刪除 mysql> delete from dep where id=2; Query OK, 1 row affected (0.00 sec) mysql> select * from dep; +----+--------+--------------------------+ | id | name | comment | +----+--------+--------------------------+ | 1 | IT | 技術能力有限部門 | | 3 | 財務 | 花錢特別多部門 | +----+--------+--------------------------+ 2 rows in set (0.00 sec) mysql> select * from emp; +----+---------+------+--------+ | id | name | sex | dep_id | +----+---------+------+--------+ | 1 | egon | male | 1 | | 2 | alex | male | 1 | | 4 | yuanhao | male | 3 | +----+---------+------+--------+ 3 rows in set (0.00 sec) # 更新父表,子表emp中的對應記錄跟着修改 mysql> update dep set id=202 where id=1; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from dep; +-----+--------+--------------------------+ | id | name | comment | +-----+--------+--------------------------+ | 3 | 財務 | 花錢特別多部門 | | 202 | IT | 技術能力有限部門 | +-----+--------+--------------------------+ 2 rows in set (0.00 sec) mysql> select * from emp; +----+---------+------+--------+ | id | name | sex | dep_id | +----+---------+------+--------+ | 1 | egon | male | 202 | | 2 | alex | male | 202 | | 4 | yuanhao | male | 3 | +----+---------+------+--------+ 3 rows in set (0.00 sec)
可是在實際運用中,最好不要經過foreign key直接創建表的耦合關係,考慮程序的擴展性來講,最好是從應用程序裏,作兩個表的映射關係,兩個表只是有邏輯關係。
分析步驟:
(1)先站在左表的角度去找——是否左表的多條記錄能夠對應右表的一條記錄,若是是,則證實左表的一個字段foreign key右表一個字段(一般是id)。
(2)再站在右表的角度去找——是否右表的多條記錄能夠對應左表的一條記錄,若是是,則證實右表的一個字段foreign key左表一個字段(一般是id)。
總結:
多對一:若是隻有步驟1成立,則是左表多對一右表
若是隻有步驟2成立,則是右表多對一左表
多對多:若是步驟1和步驟2同時成立,證實這兩張表示一個雙向的多對一,即多對多。須要定義一個這兩張表的關係來專門存放兩者的關係。
一對一:若是1和2都不成立,而是左表的一條記錄惟一對應右表的一條記錄,反之亦然。這種狀況很簡單,就是在左表foreign key右表的基礎上,將左表的外鍵字段設置成unique便可。
#一對多或稱爲多對一 三張表:出版社,做者信息,書 一對多(或多對一):一個出版社能夠出版多本書 關聯方式:foreign key
mysql> create table press( -> id int primary key auto_increment, -> name varchar(20) -> ); Query OK, 0 rows affected (0.01 sec) mysql> create table book( -> id int primary key auto_increment, -> name varchar(20), -> press_id int not null, -> foreign key(press_id) references press(id) -> on delete cascade -> on update cascade -> ); Query OK, 0 rows affected (0.01 sec) mysql> insert into press(name) values -> ('北京工業地雷出版社'), -> ('人民音樂很差聽出版社'), -> ('知識產權沒有用出版社') -> ; Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> insert into book(name,press_id) values -> ('九陽神功',1), -> ('九陰真經',2), -> ('九陰白骨爪',2), -> ('獨孤九劍',3), -> ('降龍十巴掌',2), -> ('葵花寶典',3) -> ; Query OK, 6 rows affected (0.00 sec) Records: 6 Duplicates: 0 Warnings: 0 mysql> select * from press; +----+--------------------------------+ | id | name | +----+--------------------------------+ | 1 | 北京工業地雷出版社 | | 2 | 人民音樂很差聽出版社 | | 3 | 知識產權沒有用出版社 | +----+--------------------------------+ 3 rows in set (0.00 sec) mysql> select * from book; +----+-----------------+----------+ | id | name | press_id | +----+-----------------+----------+ | 1 | 九陽神功 | 1 | | 2 | 九陰真經 | 2 | | 3 | 九陰白骨爪 | 2 | | 4 | 獨孤九劍 | 3 | | 5 | 降龍十巴掌 | 2 | | 6 | 葵花寶典 | 3 | +----+-----------------+----------+ 6 rows in set (0.00 sec)
#多對多 三張表:出版社,做者信息,書 多對多:一個做者能夠寫多本書,一本書也能夠有多個做者,雙向的一對多,即多對多 關聯方式:foreign key+一張新的表
多對多的狀況下,沒法像多對一同樣,多設置一個對應字段並設置爲外鍵。必須創一個存放二者關係的表,一個字段關聯左表id,一個字段關聯右表id,這樣就解決了多對多的問題。
mysql> select * from book; +----+-----------------+----------+ | id | name | press_id | +----+-----------------+----------+ | 1 | 九陽神功 | 1 | | 2 | 九陰真經 | 2 | | 3 | 九陰白骨爪 | 2 | | 4 | 獨孤九劍 | 3 | | 5 | 降龍十巴掌 | 2 | | 6 | 葵花寶典 | 3 | +----+-----------------+----------+ 6 rows in set (0.00 sec) mysql> mysql> mysql> mysql> mysql> create table author( -> id int primary key auto_increment, -> name varchar(20) -> ); Query OK, 0 rows affected (0.02 sec) #這張表就存放做者表與書表的關係,即查詢兩者的關係查這表就能夠了 mysql> create table author2book( -> id int not null unique auto_increment, -> author_id int not null, -> book_id int not null, -> constraint fk_author foreign key(author_id) references author(id) # constraint爲外鍵取名fk_author -> on delete cascade -> on update cascade, -> constraint fk_book foreign key(book_id) references book(id) # book_id關聯book表的id字段 -> on delete cascade -> on update cascade, -> primary key(author_id,book_id) -> ); Query OK, 0 rows affected (0.02 sec) #每一個做者與本身的表明做以下 1 egon: 1 九陽神功 2 九陰真經 3 九陰白骨爪 4 獨孤九劍 5 降龍十巴掌 6 葵花寶典 2 alex: 1 九陽神功 6 葵花寶典 3 yuanhao: 4 獨孤九劍 5 降龍十巴掌 6 葵花寶典 4 wpq: 1 九陽神功 mysql> #插入四個做者,id依次排開 mysql> insert into author(name) values('egon'),('alex'),('yuanhao'),('wpq'); Query OK, 4 rows affected (0.01 sec) Records: 4 Duplicates: 0 Warnings: 0 # 寫入做者、書籍對應關係 mysql> insert into author2book(author_id,book_id) values -> (1,1), -> (1,2), -> (1,3), -> (1,4), -> (1,5), -> (1,6), -> (2,1), # alex,九陽神功 -> (2,6), -> (3,4), # yuanhao,獨孤九劍 -> (3,5), -> (3,6), -> (4,1); # wpq,九陽神功 Query OK, 12 rows affected (0.01 sec) Records: 12 Duplicates: 0 Warnings: 0 mysql> select * from author2book; +----+-----------+---------+ | id | author_id | book_id | +----+-----------+---------+ | 1 | 1 | 1 | | 2 | 1 | 2 | | 3 | 1 | 3 | | 4 | 1 | 4 | | 5 | 1 | 5 | | 6 | 1 | 6 | | 7 | 2 | 1 | | 8 | 2 | 6 | | 9 | 3 | 4 | | 10 | 3 | 5 | | 11 | 3 | 6 | | 12 | 4 | 1 | +----+-----------+---------+ 12 rows in set (0.00 sec)
#一對一 兩張表:學生表和客戶表 一對一:一個學生是一個客戶,一個客戶有可能變成一個學校,即一對一的關係 關聯方式:foreign key+unique
分析學生和客戶的關係,學生必定是一個客戶,客戶不是學生,但有可能成爲一個學生。所以必須用student來foreign key 表customer。
# 先創建客戶表,學生來自客戶 mysql> create table customer( -> id int primary key auto_increment, -> name varchar(20) not null, -> qq varchar(10) not null, -> phone char(16) not null -> ); Query OK, 0 rows affected (0.01 sec) # 創建學生表 mysql> create table student( -> id int primary key auto_increment, # 學號 -> class_name varchar(20) not null, # 班級 -> customer_id int unique, # 該字段必定要是惟一的,加了unique則學生和客戶一一對應 -> foreign key(customer_id) references customer(id) # 這張表的customer_id關聯客戶表的id字段 -> on delete cascade -> on update cascade -> ); Query OK, 0 rows affected (0.02 sec) # 增長客戶 mysql> insert into customer(name,qq,phone) values ('李飛機','31811231',13811341220), ('王大炮','123123123',15213146809), -> ('李飛機','31811231',13811341220), -> ('王大炮','123123123',15213146809), -> ('守榴彈','283818181',1867141331), ('守榴彈','283818181',1867141331), -> ('吳坦克','283818181',1851143312), -> ('贏火箭','888818181',1861243314), -> ('戰地雷','112312312',18811431230) -> ; Query OK, 6 rows affected (0.01 sec) Records: 6 Duplicates: 0 Warnings: 0 #增長學生 mysql> insert into student(class_name,customer_id) values -> ('脫產3班',3), -> ('週末19期',4), -> ('週末19期',5) -> ; Query OK, 3 rows affected (0.01 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from customer; +----+-----------+-----------+-------------+ | id | name | qq | phone | +----+-----------+-----------+-------------+ | 1 | 李飛機 | 31811231 | 13811341220 | | 2 | 王大炮 | 123123123 | 15213146809 | | 3 | 守榴彈 | 283818181 | 1867141331 | | 4 | 吳坦克 | 283818181 | 1851143312 | | 5 | 贏火箭 | 888818181 | 1861243314 | | 6 | 戰地雷 | 112312312 | 18811431230 | +----+-----------+-----------+-------------+ 6 rows in set (0.00 sec) mysql> select * from student; +----+-------------+-------------+ | id | class_name | customer_id | +----+-------------+-------------+ | 1 | 脫產3班 | 3 | | 2 | 週末19期 | 4 | | 3 | 週末19期 | 5 | +----+-------------+-------------+ 3 rows in set (0.00 sec)
例一:一個用戶只有一個博客 用戶表: id name 1 egon 2 alex 3 wupeiqi 博客表 fk+unique id url name_id 1 xxxx 1 2 yyyy 3 3 zzz 2 例二:一個管理員惟一對應一個用戶 用戶表: id user password 1 egon xxxx 2 alex yyyy 管理員表: fk+unique id user_id password 1 1 xxxxx 2 2 yyyyy
練習:帳號信息表,用戶組,主機表,主機組。
#用戶表 create table user( id int not null unique auto_increment, username varchar(20) not null, password varchar(50) not null, primary key(username,password) ); insert into user(username,password) values ('root','123'), ('egon','456'), ('alex','alex3714') ; #用戶組表 create table usergroup( id int primary key auto_increment, groupname varchar(20) not null unique ); insert into usergroup(groupname) values ('IT'), ('Sale'), ('Finance'), ('boss') ; #主機表 create table host( id int primary key auto_increment, ip char(15) not null unique default '127.0.0.1' ); insert into host(ip) values ('172.16.45.2'), ('172.16.31.10'), ('172.16.45.3'), ('172.16.31.11'), ('172.10.45.3'), ('172.10.45.4'), ('172.10.45.5'), ('192.168.1.20'), ('192.168.1.21'), ('192.168.1.22'), ('192.168.2.23'), ('192.168.2.223'), ('192.168.2.24'), ('192.168.3.22'), ('192.168.3.23'), ('192.168.3.24') ; #業務線表 create table business( id int primary key auto_increment, business varchar(20) not null unique ); insert into business(business) values ('輕鬆貸'), ('隨便花'), ('大富翁'), ('窮一輩子') ; #建關係:user與usergroup create table user2usergroup( id int not null unique auto_increment, user_id int not null, group_id int not null, primary key(user_id,group_id), foreign key(user_id) references user(id), foreign key(group_id) references usergroup(id) ); insert into user2usergroup(user_id,group_id) values (1,1), (1,2), (1,3), (1,4), (2,3), (2,4), (3,4) ; #建關係:host與business create table host2business( id int not null unique auto_increment, host_id int not null, business_id int not null, primary key(host_id,business_id), foreign key(host_id) references host(id), foreign key(business_id) references business(id) ); insert into host2business(host_id,business_id) values (1,1), (1,2), (1,3), (2,2), (2,3), (3,4) ; #建關係:user與host create table user2host( id int not null unique auto_increment, user_id int not null, host_id int not null, primary key(user_id,host_id), foreign key(user_id) references user(id), foreign key(host_id) references host(id) ); insert into user2host(user_id,host_id) values (1,1), (1,2), (1,3), (1,4), (1,5), (1,6), (1,7), (1,8), (1,9), (1,10), (1,11), (1,12), (1,13), (1,14), (1,15), (1,16), (2,2), (2,3), (2,4), (2,5), (3,10), (3,11), (3,12) ;
# 建立用戶表 mysql> create table user( -> id int not null unique auto_increment, # 用戶的id非空、惟一且自增 -> username varchar(20) not null, -> password varchar(50) not null, -> primary key(username,password) # 複合主鍵:用戶名+密碼 -> ); Query OK, 0 rows affected (0.03 sec) # 插入用戶數據 mysql> insert into user(username,password) values -> ('root', '123'), -> ('egon', '456'), -> ('alex', 'alex3714') -> ; Query OK, 3 rows affected (0.01 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from user; +----+----------+----------+ | id | username | password | +----+----------+----------+ | 1 | root | 123 | | 2 | egon | 456 | | 3 | alex | alex3714 | +----+----------+----------+ 3 rows in set (0.00 sec) # 建立用戶組 mysql> create table usergroup( -> id int primary key auto_increment, # 用戶組id設爲主鍵,且自增 -> groupname varchar(20) not null unique # 用戶組名非空且惟一 -> ); Query OK, 0 rows affected (0.03 sec) # 插入用戶組數據 mysql> insert into usergroup(groupname) values -> ('IT'), -> ('Sale'), -> ('Finance'), -> ('boss') -> ; Query OK, 4 rows affected (0.00 sec) Records: 4 Duplicates: 0 Warnings: 0 mysql> select * from usergroup; +----+-----------+ | id | groupname | +----+-----------+ | 4 | boss | | 3 | Finance | | 1 | IT | | 2 | Sale | +----+-----------+ 4 rows in set (0.00 sec) # 建立主機表 mysql> create table host( -> id int primary key auto_increment, # 主機表id爲主鍵、自增 -> ip char(15) not null unique default '127.0.0.1' # ip地址非空、惟1、設置了默認值 -> ); Query OK, 0 rows affected (0.02 sec) mysql> insert into host(ip) values -> ('172.16.45.2'), -> ('172.16.31.10'), -> ('172.16.45.3'), -> ('172.16.31.11'), -> ('172.10.45.3'), -> ('172.10.45.4'), -> ('172.10.45.5'), -> ('192.168.1.20'), -> ('192.168.1.21'), -> ('192.168.1.22'), -> ('192.168.2.23'), -> ('192.168.2.223'), -> ('192.168.2.24'), -> ('192.168.3.22'), -> ('192.168.3.23'), -> ('192.168.3.24') -> ; Query OK, 16 rows affected (0.00 sec) Records: 16 Duplicates: 0 Warnings: 0 mysql> select * from host; +----+---------------+ | id | ip | +----+---------------+ | 5 | 172.10.45.3 | | 6 | 172.10.45.4 | | 7 | 172.10.45.5 | | 2 | 172.16.31.10 | | 4 | 172.16.31.11 | | 1 | 172.16.45.2 | | 3 | 172.16.45.3 | | 8 | 192.168.1.20 | | 9 | 192.168.1.21 | | 10 | 192.168.1.22 | | 12 | 192.168.2.223 | | 11 | 192.168.2.23 | | 13 | 192.168.2.24 | | 14 | 192.168.3.22 | | 15 | 192.168.3.23 | | 16 | 192.168.3.24 | +----+---------------+ 16 rows in set (0.00 sec) # 建立業務表 mysql> create table business( -> id int primary key auto_increment, # 業務id爲主鍵、自增 -> business varchar(20) not null unique # 業務非空、惟一 -> ); Query OK, 0 rows affected (0.02 sec) mysql> insert into business(business) values -> ('輕鬆貸'), -> ('隨便花'), -> ('大富翁'), -> ('窮一輩子') -> ; Query OK, 4 rows affected (0.00 sec) Records: 4 Duplicates: 0 Warnings: 0 mysql> select * from business; +----+-----------+ | id | business | +----+-----------+ | 3 | 大富翁 | | 4 | 窮一輩子 | | 1 | 輕鬆貸 | | 2 | 隨便花 | +----+-----------+ 4 rows in set (0.00 sec) # 建關係:user和usergroup 多對多 mysql> create table user2usergroup( -> id int not null unique auto_increment, -> user_id int not null, -> group_id int not null, -> primary key(user_id, group_id), # 指定並建立複合主鍵、約束爲不爲空且惟一 -> foreign key(user_id) references user(id), # user_id關聯用戶表id字段 -> foreign key(group_id) references usergroup(id) # group_id關聯用戶組id字段 -> ); Query OK, 0 rows affected (0.03 sec) mysql> insert into user2usergroup(user_id,group_id) values -> (1,1), -> (1,2), -> (1,3), -> (1,4), -> (2,3), -> (2,4), -> (3,4) -> ; Query OK, 7 rows affected (0.00 sec) Records: 7 Duplicates: 0 Warnings: 0 mysql> select * from user2usergroup; +----+---------+----------+ | id | user_id | group_id | +----+---------+----------+ | 1 | 1 | 1 | | 2 | 1 | 2 | | 3 | 1 | 3 | | 4 | 1 | 4 | | 5 | 2 | 3 | | 6 | 2 | 4 | | 7 | 3 | 4 | +----+---------+----------+ 7 rows in set (0.00 sec) # 建關係:host與business 多對多 mysql> create table host2business( -> id int not null unique auto_increment, -> host_id int not null, -> business_id int not null, -> primary key(host_id,business_id), # 指定並建立複合主鍵、約束爲不爲空且惟一 -> foreign key(host_id) references host(id), # host_id關聯用戶id字段 -> foreign key(business_id) references business(id) # business_id關聯業務id字段 -> ); Query OK, 0 rows affected (0.02 sec) mysql> insert into host2business(host_id, business_id) values -> (1,1), -> (1,2), -> (1,3), -> (2,2), -> (2,3), -> (3,4); Query OK, 6 rows affected (0.01 sec) Records: 6 Duplicates: 0 Warnings: 0 # 建關係:user與host 多對多 mysql> create table user2host( -> id int not null unique auto_increment, -> user_id int not null, -> host_id int not null, -> primary key(user_id,host_id), -> foreign key(user_id) references user(id), # user_id關聯用戶id字段 -> foreign key(host_id) references host(id) # host_id關聯主機id字段 -> ); Query OK, 0 rows affected (0.03 sec) mysql> insert into user2host(user_id,host_id) values -> (1,1), -> (1,2), -> (1,3), -> (1,4), -> (1,5), -> (1,6), -> (1,7), -> (1,8), -> (1,9), -> (1,10), -> (1,11), -> (1,12), -> (1,13), -> (1,14), -> (1,15), -> (1,16), -> (2,2), -> (2,3), -> (2,4), -> (2,5), -> (3,10), -> (3,11), -> (3,12) -> ; Query OK, 23 rows affected (0.00 sec) Records: 23 Duplicates: 0 Warnings: 0
做業:
mysql> create database db2; Query OK, 1 row affected (0.00 sec) mysql> use db2 Database changed mysql> show tables; Empty set (0.00 sec) mysql> create table class( -> cid int primary key auto_increment, -> caption char(20) not null -> ); Query OK, 0 rows affected (0.02 sec) mysql> insert into class(caption) values -> ('三年二班'), -> ('一年三班'), -> ('三年一班'); Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from class; +-----+--------------+ | cid | caption | +-----+--------------+ | 1 | 三年二班 | | 2 | 一年三班 | | 3 | 三年一班 | +-----+--------------+ 3 rows in set (0.00 sec) mysql> create table student( -> sid int primary key auto_increment, -> sname char(20) not null, -> gender enum('男','女') not null, -> class_id int not null, -> foreign key(class_id) references class(cid) -> on delete cascade -> on update cascade -> ); Query OK, 0 rows affected (0.01 sec) mysql> insert into student(sname,gender,class_id) values -> ('鋼蛋','女',1), -> ('鐵錘','女',1), -> ('山炮','男',2); Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from student; +-----+--------+--------+----------+ | sid | sname | gender | class_id | +-----+--------+--------+----------+ | 1 | 鋼蛋 | 女 | 1 | | 2 | 鐵錘 | 女 | 1 | | 3 | 山炮 | 男 | 2 | +-----+--------+--------+----------+ 3 rows in set (0.00 sec) mysql> create table teacher( -> tid int primary key auto_increment, -> tname char(20) not null -> ); Query OK, 0 rows affected (0.02 sec) mysql> insert into teacher(tname) values -> ('波多'), -> ('蒼空'), -> ('飯島'); Query OK, 3 rows affected (0.01 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from teacher; +-----+--------+ | tid | tname | +-----+--------+ | 1 | 波多 | | 2 | 蒼空 | | 3 | 飯島 | +-----+--------+ 3 rows in set (0.00 sec) mysql> create table course( -> cid int primary key auto_increment, -> cname char(20) not null, -> teacher_id int not null, -> foreign key(teacher_id) references teacher(tid) -> on delete cascade -> on update cascade -> ); Query OK, 0 rows affected (0.01 sec) mysql> insert into course(cname,teacher_id) values -> ('生物',1),('體育',1),('物理',2); Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from course; +-----+--------+------------+ | cid | cname | teacher_id | +-----+--------+------------+ | 1 | 生物 | 1 | | 2 | 體育 | 1 | | 3 | 物理 | 2 | +-----+--------+------------+ 3 rows in set (0.00 sec) mysql> create table score( -> sid int not null unique auto_increment, -> student_id int not null, -> corse_id int not null, -> foreign key(student_id) references student(sid) -> on delete cascade -> on update cascade, -> foreign key(corse_id) references course(cid) -> on delete cascade -> on update cascade, -> number int not null, -> primary key(student_id, corse_id) -> ); Query OK, 0 rows affected (0.01 sec) mysql> insert into score(student_id, corse_id, number) values -> (1,1,60),(1,2,59),(2,2,100); Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from score; +-----+------------+----------+--------+ | sid | student_id | corse_id | number | +-----+------------+----------+--------+ | 1 | 1 | 1 | 60 | | 2 | 1 | 2 | 59 | | 3 | 2 | 2 | 100 | +-----+------------+----------+--------+ 3 rows in set (0.00 sec)