數據庫開發——MySQL——foreign key

五,foreign key

foreign key是跟外部表關聯的字段。

foreign key理解

學生信息表有三個字段:學號、姓名、年級,學校有四個年級,但是有3萬多學生,那就意味着年級這個字段的信息要重複存儲,要存儲的年級信息越長就越浪費資源。

可以通過定義一個年級表關聯學生信息表,這樣每個學生的年級就只需要存儲所處年級在年級信息表中的id,這個外表關聯關係,就是通過foreign key定義的。

既然學生的年級信息要關聯到年級信息,所以在創建學生信息表之前年級信息表必須存在,也就是必須先創建年級信息表,並且表的類型必須是innodb存儲引擎,且被關聯的字段必須是另一個表中的unique字段。

create table grade(
	grade_year year primary key,
	name varchar(20) not null
	)engine=innodb;

create table student(
	id int primary key,
	name varchar(20) not null,
	grade_id year,
	constraint fk_grade_id foreign key(grade_id) references grade(grade_year)
	on delete cascade	# 同步刪除
	on update cascade	# 同步更新

insert into grade values 
	(2019, "2019 grade"), 
	(2018, "2018 grade"), 
	(2017, "2017 grade"), 
	(2016, "2016 grade");

insert into student values
	(1, "Alex", 2018),
	(2, "Coco", 2019),
	(3, "alex", 2018),
	(4, "coco", 2019);

select * from student;
select * from grade;

delete from grade where grade_year=2019;
select * from student;

update grade set grade_year=2019 where grade_year=2018;
select * from student;

執行結果爲:

mysql> create table grade(
    -> grade_year year primary key,
    -> name varchar(20) not null
    -> )engine=innodb;
Query OK, 0 rows affected (0.85 sec)

mysql> create table student(
    -> id int primary key,
    -> name varchar(20) not null,
    -> grade_id year,
    -> constraint fk_grade_id foreign key(grade_id) references grade(grade_year)
    -> on delete cascade
    -> on update cascade
    -> )engine=innodb;
Query OK, 0 rows affected (0.66 sec)

mysql> insert into grade values (2019, "2019 grade"), (2018, "2018 grade"), (2017, "2017 grade"), (2016, "2016 grade");
Query OK, 4 rows affected (0.15 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> insert into student values
    -> (1, "Alex", 2018),
    -> (2, "Coco", 2019),
    -> (3, "alex", 2018),
    -> (4, "coco", 2019);
Query OK, 4 rows affected (0.22 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select * from student;
+----+------+----------+
| id | name | grade_id |
+----+------+----------+
|  1 | Alex |     2018 |
|  2 | Coco |     2019 |
|  3 | alex |     2018 |
|  4 | coco |     2019 |
+----+------+----------+
4 rows in set (0.00 sec)

mysql> select * from grade;
+------------+------------+
| grade_year | name       |
+------------+------------+
|       2016 | 2016 grade |
|       2017 | 2017 grade |
|       2018 | 2018 grade |
|       2019 | 2019 grade |
+------------+------------+
4 rows in set (0.00 sec)

mysql> delete from grade where grade_year=2019;
Query OK, 1 row affected (0.27 sec)

mysql> select * from student;
+----+------+----------+
| id | name | grade_id |
+----+------+----------+
|  1 | Alex |     2018 |
|  3 | alex |     2018 |
+----+------+----------+
2 rows in set (0.00 sec)

mysql> update grade set grade_year=2019 where grade_year=2018;
Query OK, 1 row affected (0.07 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from student;
+----+------+----------+
| id | name | grade_id |
+----+------+----------+
|  1 | Alex |     2019 |
|  3 | alex |     2019 |
+----+------+----------+
2 rows in set (0.00 sec)

如何找出兩表之間的關係

分析步驟:

1、先站在左表的角度去找

是否左表的多條記錄可以對應右表的一條記錄,如果是,則證明左表的一個字段foreign key 右表一個字段(通常是id)

2、再站在右表的角度去找

是否右表的多條記錄可以對應左表的一條記錄,如果是,則證明右表的一個字段foreign key 左表一個字段(通常是id)

3、總結:

#多對一:
如果只有步驟1成立,則是左表多對一右表
如果只有步驟2成立,則是右表多對一左表

#多對多
如果步驟1和2同時成立,則證明這兩張表時一個雙向的多對一,即多對多,需要定義一個這兩張表的關係表來專門存放二者的關係

#一對一:
如果1和2都不成立,而是左表的一條記錄唯一對應右表的一條記錄,反之亦然。這種情況很簡單,就是在左表foreign key右表的基礎上,將左表的外鍵字段設置成unique即可

建立兩表之間的關係

三張表:出版社,作者信息,書

一對多或多對一

一對多(或多對一):一個出版社可以出版多本書

關聯方式:foreign key

create table press(
	id int primary key auto_increment,
	name varchar(20));

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


insert into press(name) values
	('北京工業地雷出版社'),
	('人民音樂不好聽出版社'),
	('知識產權沒有用出版社');

insert into book(name,press_id) values
	('九陽神功',1),
	('九陰真經',2),
	('九陰白骨爪',2),
	('獨孤九劍',3),
	('降龍十巴掌',2),
	('葵花寶典',3);

select * from press;

select * from book;

執行結果爲:

mysql> create table press(
	id int primary key auto_increment,
	name varchar(20));

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.50 sec)

mysql> insert into press(name) values
    -> ('北京工業地雷出版社'),
    -> ('人民音樂不好聽出版社'),
    -> ('知識產權沒有用出版社');
Query OK, 3 rows affected (0.18 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.10 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)
Query OK, 0 rows affected (0.62 sec)

多堆多

多對多:一個作者可以寫多本書,一本書也可以有多個作者,雙向的一對多,即多對多
  
關聯方式:foreign key+一張新的表

create table author(
	id int primary key auto_increment,
	name varchar(20));

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)
	on delete cascade
	on update cascade,
	constraint fk_book foreign key(book_id) references book(id)
	on delete cascade
	on update cascade,
	primary key(author_id,book_id));

insert into author(name) values('Alex'),('Coco'),('BeiBei'),('Python');

insert into author2book(author_id,book_id) values
(1,1),(1,2),(1,3),(1,4),(1,5),(1,6),(2,1),(2,6),(3,4),(3,5),(3,6),(4,1);

select * from author;
select * from author2book;
select * from book;

執行結果爲:

mysql> create table author(
    -> id int primary key auto_increment,
    -> name varchar(20));
Query OK, 0 rows affected (0.52 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)
    -> on delete cascade
    -> on update cascade,
    -> constraint fk_book foreign key(book_id) references book(id)
    -> on delete cascade
    -> on update cascade,
    -> primary key(author_id,book_id));
Query OK, 0 rows affected (0.60 sec)

mysql> insert into author(name) values('Alex'),('Coco'),('BeiBei'),('Python');
Query OK, 4 rows affected (0.08 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql>
mysql> insert into author2book(author_id,book_id) values
    -> (1,1),(1,2),(1,3),(1,4),(1,5),(1,6),(2,1),(2,6),(3,4),(3,5),(3,6),(4,1);
Query OK, 12 rows affected (0.06 sec)
Records: 12  Duplicates: 0  Warnings: 0

mysql> select * from author;
+----+--------+
| id | name   |
+----+--------+
|  1 | Alex   |
|  2 | Coco   |
|  3 | BeiBei |
|  4 | Python |
+----+--------+
4 rows in set (0.00 sec)

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)

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)
發佈了685 篇原創文章 · 獲贊 157 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章