一、等值連接 .....=......
select * from 表1 as b1,表2 as b2 where b1.字段=b2.字段
再有其他條件,直接加在后邊即可
select * from stu,course,score
where stu.stuid=score.stuid and course.cid=score.cid
- 必須要出現(xiàn)后邊的等值條件,按照=的兩邊,取交集
- 不會出現(xiàn)新表,只是一個顯示結(jié)果
- 先連接成一個笛卡爾積(生成記錄總數(shù)=表1的總數(shù)*表2的總數(shù)),在根據(jù)條件篩選
- 會產(chǎn)生臨時表,占內(nèi)存
二、內(nèi)連接 inner join.....on.......
select * from 表1
inner join 表2 on 表1.字段=表2.字段
where 條件
order by .....
limit ....
select * from stu
inner join score on where stu.stuid=score.stuid
inner join course on course.cid=score.cid
where stu.name='王昭君'
#先兩個表連接,在和第三個表連接
#*要寫成列名時,列名要加前綴表明是哪個表的,有重復(fù)的
#起別名,只能用別名
- 先根據(jù)條件篩選,在連接兩個表
- 不會產(chǎn)生臨時表,不占內(nèi)存,性能高一些

img_innerjoin.gif
三、左連接 left join.....on.....
select * from 表1
left join 表2 on 表1.字段=表2.字段
select * from stu
left join score on where stu.stuid=score.stuid
#join前邊生成的結(jié)果作為左表
left join course on course.cid=score.cid
#查詢所有學(xué)生的成績,包括沒有成績的學(xué)生,需要顯示課程名
- join前面生成的結(jié)果作為左邊,join后面的是右表,把左表的數(shù)據(jù)全部顯示
- 取左表所有結(jié)果,右表有符合的連接到一起成一條數(shù)據(jù),沒有符合的右表部分字段就都填上null成一條數(shù)據(jù)
- 和內(nèi)連接的區(qū)別就是,內(nèi)連接沒找到符合的不會顯示null,該條不會存在表中,所以只要有右表不符合的情況,左表結(jié)果不會全部顯示

img_leftjoin.gif
四、右連接 right join....on.....
select * from 表1
right join 表2 on 表1.字段=表2.字段
select * from score
right join course on where course.cid=score.cid
left join stu on stu.stuid=score.stuid
#查詢所有課程的成績,包括沒有成績的課程,需要顯示學(xué)生信息
- join前面生成的結(jié)果作為左邊,join后面的是右表,把右表的數(shù)據(jù)全部顯示
- 取右表所有結(jié)果,左表有符合的連接到一起成一條數(shù)據(jù),沒有符合的左表部分字段就都填上null成一條數(shù)據(jù)

img_rightjoin.gif
使用左右連接(題目中包含所有,沒有字眼需要用到左右連接)
- 只要明白那個是左表、右表;
- 那個需要所有結(jié)果;
- 那個需要null值;
五、自關(guān)聯(lián)
-
一個表關(guān)聯(lián)多次
select * from areas as sheng,areas as shi
where sheng.aid=shi.pid
select * from areas as sheng,areas as shi,areas as qu
where sheng.aid=shi.pid and shi.aid=qu.pid
- 數(shù)據(jù)之間有上下級關(guān)系
- 在一個表中存儲所有數(shù)據(jù)
- 從一個表中查詢多次,必須起別名
