多變關(guān)聯(lián)的實(shí)現(xiàn)方式有hash join,merge join,nested loop join 方式锰茉,具體使用那種內(nèi)型的連接缕碎,主要依據(jù):
1.當(dāng)前的優(yōu)化器模式(all_rows和rule)
2.取決于表的大小
3.取決于關(guān)聯(lián)字段是否有索性
4.取決于關(guān)聯(lián)字段是否排序
Hash? join散列連接,優(yōu)化器選擇較小的表(數(shù)據(jù)量少的表)利用連接鍵(join key)在內(nèi)存中建立散列表灼捂,將數(shù)據(jù)存儲(chǔ)到hash列表中离例,然后掃描較大的表
select A.*,B.* from A left join B on a.id=b.id。
先是從A表讀取一條記錄悉稠,用on條件匹配B表的記錄宫蛆,行成n行(包括重復(fù)行)如果B表沒(méi)有與匹配的數(shù)據(jù),則select中B表的字段顯示為空,接著讀取A表的下一條記錄的猛,right join類似耀盗。
left join基本是A表全部掃描,在表關(guān)鍵中不建議使用子查詢作為副表卦尊,比如select A.*,B.*from A left join (select * from b where b.type=1 )這樣A表是全表掃描叛拷,B表也是全表掃描。若果查詢慢岂却,可以考慮關(guān)聯(lián)的字段都建索引忿薇,將不必要的排序去掉,排序會(huì)導(dǎo)致運(yùn)行慢很多淌友。
主副表?xiàng)l件過(guò)濾:
table a(id, type):
id? ? type
----------------------------------
1? ? ? 1? ? ? ?
2? ? ? 1? ? ? ? ?
3? ? ? 2? ?
表b結(jié)構(gòu)和數(shù)據(jù)
table b(id, class):
id? ? class
---------------------------------
1? ? ? 1
2? ? ? 2
Sql語(yǔ)句1: select a.*, b.* from a left join b on a.id = b.id and a.type = 1;
執(zhí)行結(jié)果為:
a.id? ? a.type? ? b.id? ? b.class
----------------------------------------
1? ? ? ? 1? ? ? ? ? ? 1? ? ? ? 1
2? ? ? ? 1? ? ? ? ? ? 2? ? ? ? 2
3? ? ? ? 2
a.type=1沒(méi)有起作用
sql語(yǔ)句2:
select a.*, b.* from a left join b on a.id = b.id where a.type = 1;
執(zhí)行結(jié)果為:
a.id? ? a.type? ? b.id? ? b.class
----------------------------------------
1? ? ? ? 1? ? ? ? ? ? 1? ? ? ? 1
2? ? ? ? 1? ? ? ? ? ? 2? ? ? ? 2
sql語(yǔ)句3:
select a.*, b.* from a left join b on a.id = b.id and b.class = 1;
執(zhí)行結(jié)果為:
a.id? ? a.type? ? b.id? ? b.class
----------------------------------------
1? ? ? ? 1? ? ? ? ? ? 1? ? ? ? 1
2? ? ? ? 1? ? ? ? ? ?
3? ? ? ? 2
b.class=1條件過(guò)濾成功煌恢。
結(jié)論:left join中骇陈,左表(主表)的過(guò)濾條件在on后不起作用震庭,需要在where中添加。右表(副表)的過(guò)濾條件在on后面起作用你雌。
Mysql join原理:
Mysql join采用了Nested Loop join的算法器联,
###坐車 回去補(bǔ)充二汛。