存儲(chǔ)關(guān)系
entry之間如果有某種關(guān)系也要將關(guān)系存儲(chǔ)下來(lái)。
一對(duì)一:不常使用,一般在做優(yōu)化時(shí)使用。
一對(duì)多:最常用,將關(guān)系存儲(chǔ)在“多”這邊。
多對(duì)多:兩邊都要存儲(chǔ)關(guān)系。
建立關(guān)系

1.alter
alter table scores add constraint stu_sco foreign key(stuid) references student(id);
2.創(chuàng)建表時(shí)建立關(guān)系
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)容,需要注意的是外鍵約束,如果主表中沒(méi)有從表要插入的數(shù)據(jù),則會(huì)拋出異。
刪除 / 修改 數(shù)據(jù)
直接刪除從表中的數(shù)據(jù),參考上一節(jié)內(nèi)容。
刪除主表中的數(shù)據(jù)時(shí)需要考慮級(jí)聯(lián)
1.在從表中刪除數(shù)據(jù)時(shí),恰好主表中用到了這條數(shù)據(jù),則會(huì)拋出異常。
2.推薦使用邏輯刪除,可以解決這個(gè)問(wèn)題
3.可以在創(chuàng)建表時(shí)指定級(jí)聯(lián)操作,也可以在創(chuàng)建表之后再修改外鍵的級(jí)聯(lián)操作
restrict:限制,默認(rèn)值,拋異常。
cascade:級(jí)聯(lián),如果主表的記錄刪除掉,則從表中的相關(guān)紀(jì)錄都將被刪除。
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;
查詢(xún)
連接查詢(xún)
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;
當(dāng)需要對(duì)有關(guān)系的多張表進(jìn)行查詢(xún)時(shí),需要使用join。
關(guān)鍵字:
表1 inner join 表2:內(nèi)連接,表1與表2匹配的行會(huì)出現(xiàn)在結(jié)果中。
表1 right join 表2:右連接,表1與表2匹配的行會(huì)出現(xiàn)在結(jié)果中,外加表2中獨(dú)有的數(shù)據(jù),為對(duì)應(yīng)的數(shù)據(jù)使用null填充。
表1 left join 表2:左連接,表1與表2匹配的行會(huì)出現(xiàn)在結(jié)果中,外加表1中獨(dú)有的數(shù)據(jù),為對(duì)應(yīng)的數(shù)據(jù)使用null填充。
語(yǔ)法:
select ...
from 表1
right | left | inner join 表2 on [表1與表2的關(guān)系]
right | left | inner join 表3 on [表1與表3的關(guān)系] | [表2與表3的關(guān)系];
所以也可以這樣寫(xiě)查詢(xún)語(yǔ)句
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;
自關(guān)聯(lián)
例:

?????分析表結(jié)構(gòu)可知,這三張表的結(jié)構(gòu)幾乎一樣,并且創(chuàng)建一張新表的1代價(jià)是十分大的,所以我們可以考慮將這三張表合并為一張,這時(shí)字段pid就會(huì)指向本表的id,即為自關(guān)聯(lián),以此來(lái)提高數(shù)據(jù)庫(kù)的性能。
create table areas(
id int primary key auto_increment not null,
title varchar(30),
pid int,
foreign key(pid) references areas(id));
查詢(xún):
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 = '河南'; //查找河南省所有的市