存儲關系
entry之間如果有某種關系也要將關系存儲下來。
一對一:不常使用,一般在做優(yōu)化時使用。
一對多:最常用,將關系存儲在“多”這邊。
多對多:兩邊都要存儲關系。
建立關系

1.alter
alter table scores add constraint stu_sco foreign key(stuid) references student(id);
2.創(chuàng)建表時建立關系
create table scores(
id int primary key auto_increment,
stuid int,
subid int,
score decimal(5,2),
foreign key(stuid) references students(id),
foreign key(subid) references subjects(id)
);
插入數(shù)據(jù)
參考上一節(jié)內(nèi)容,需要注意的是外鍵約束,如果主表中沒有從表要插入的數(shù)據(jù),則會拋出異。
刪除 / 修改 數(shù)據(jù)
直接刪除從表中的數(shù)據(jù),參考上一節(jié)內(nèi)容。
刪除主表中的數(shù)據(jù)時需要考慮級聯(lián)
1.在從表中刪除數(shù)據(jù)時,恰好主表中用到了這條數(shù)據(jù),則會拋出異常。
2.推薦使用邏輯刪除,可以解決這個問題
3.可以在創(chuàng)建表時指定級聯(lián)操作,也可以在創(chuàng)建表之后再修改外鍵的級聯(lián)操作
restrict:限制,默認值,拋異常。
cascade:級聯(lián),如果主表的記錄刪除掉,則從表中的相關紀錄都將被刪除。
set null:將外鍵置空。
no action:什么都不做。
create table scores(
id int primary key auto_increment,
stuid int,
subid int,
score decimal(5,2),
foreign key(stuid) references students(id),
foreign key(subid) references subjects(id)
on delete cascade
on update cascade
);
alter table scores add constraint stu_sco foreign key(stuid) references student(id) on delete cascade on update cascade;
查詢
連接查詢
select students.name,subjects.title,scores.score
from scores
inner join students on scores.stuid = students.id
inner join subjects on scores.subid = subjects.id;
當需要對有關系的多張表進行查詢時,需要使用join。
關鍵字:
表1 inner join 表2:內(nèi)連接,表1與表2匹配的行會出現(xiàn)在結(jié)果中。
表1 right join 表2:右連接,表1與表2匹配的行會出現(xiàn)在結(jié)果中,外加表2中獨有的數(shù)據(jù),為對應的數(shù)據(jù)使用null填充。
表1 left join 表2:左連接,表1與表2匹配的行會出現(xiàn)在結(jié)果中,外加表1中獨有的數(shù)據(jù),為對應的數(shù)據(jù)使用null填充。
語法:
select ...
from 表1
right | left | inner join 表2 on [表1與表2的關系]
right | left | inner join 表3 on [表1與表3的關系] | [表2與表3的關系];
所以也可以這樣寫查詢語句
select students.name,subjects.title,scores.score
from students
inner join scores on scores.stuid = students.id
inner join subjects on scores.subid = subjects.id;
自關聯(lián)
例:

?????分析表結(jié)構(gòu)可知,這三張表的結(jié)構(gòu)幾乎一樣,并且創(chuàng)建一張新表的1代價是十分大的,所以我們可以考慮將這三張表合并為一張,這時字段pid就會指向本表的id,即為自關聯(lián),以此來提高數(shù)據(jù)庫的性能。
create table areas(
id int primary key auto_increment not null,
title varchar(30),
pid int,
foreign key(pid) references areas(id));
查詢:
select p.title as province,c.title as city
from areas as p
inner join areas as c on c.pid = p.id
where p.title = '河南'; //查找河南省所有的市