理解mysql中的join

2021-09-26 13:29:36 字數 2181 閱讀 9766

1 兩表join時要小表驅動大表,為什麼?

user表10000條資料,class表20條資料

select * from user u left join class c on  u.userid=c.userid;

上面的結果是迴圈10000次,每次獲取user的userid到class中找與user表userid相同的記錄

,但是如果寫成下面的sql,僅僅需要迴圈20次

select * from class c left join  user u  on u.userid=c.userid;

怎麼知道誰驅動誰

left和right的正確理解: left join(左聯接) 返回包括左表中的所有記錄和右表中聯結字段相等的記錄。

right和left不影響誰驅動誰,即:

a left  join b和a right  join b都是a表驅動b表;所以如果a相對b表較小,基於小表驅動大表的原則 ,推薦上面兩種寫法

2  正確理解join後面的on條件

下面四個sql的結果和效率區分,a 1千條,b 1萬條記錄

1)select a.col1,a.col2 from a,b  where a.uid=b.uid  and a.col1='col1';

2)select a.col1,a.col2 from a inner join b  on a.uid=b.uid and a.col1='col1';

注意2是inner join:1和2輸出結果一樣,並且查詢效率也一樣,上面兩個sql完全等價;

3)select a.col1,a.col2 from a left join b  on a.uid=b.uid  and a.col1='col1';

3和2的區別是3的結果會更多,多的是a.uid存在但b.uid不存在的部分

4)select a.col1,a.col2 from a left join b  where a.uid=b.uid  and a.col1='col1';

4和3,都要做笛卡爾積,這裡3中on的含義:

以a.uid的值為標準,如果b表uid沒有對應的值,則直接返回a的內容並且不做a.col1='col1'的驗證;

如果b.uid有值,那麼會進一步要求a.col1='col1';

4中where條件是在臨時表生成好後,再對臨時表進行過濾的條件,條件不為真的就全部過濾掉,所以a表存在但b表不存在的並不會返回,所以where的結果會更少

如:table a(id, type):

id     type

----------------------------------

1      1        

2      1         

3      2         

table b(id, class):

id    class

---------------------------------

1      1

2      2

sql語句1:select a.*, b.* from a left join b on a.id = b.id and a.type = 1;

sql語句2:select a.*, b.* from a left join b on a.id = b.id where a.type = 1;

sql語句1的執行結果為:

a.id    a.type    b.id    b.class

----------------------------------------

1        1            1        1

2        1            2        2

3        2              

sql語句2的執行結果為:

a.id    a.type    b.id    b.class

----------------------------------------

1        1            1        1

2        1            2        2

所以sql1中的條件a.type=1只有在a、b兩表記錄能對應的時候(既滿足 a.id = b.id )才會生效。注意sql語句1中返回的 3 2

a.id = b.id and a.type = 1兩個條件都不滿足

mysql中join的選擇(mysql每日一講)

條件 a表100行資料 b表100行資料 假如 a join b on a.欄位1 b.欄位2 此時驅動表是a表,被驅動表示b表 1 假如b表上字段2建立了索引 那麼a表作為驅動表將會逐行掃瞄,掃瞄100次,b表上字段2有索引,因此a表每一行會讀b表的一行,這樣總掃瞄次數是100 100 200次 ...

Java中的join方法個人理解

因為今天看到一道筆試題目,就是怎麼確保多執行緒不發生死鎖問題,個人認為要確保多執行緒不發生死鎖的辦法就是讓執行緒有序的操作資源,當然我也不知道對不對,如果發現有錯,歡迎指出把。我當時想到的就是使用join方法使用,然後就發現自己以前就是知道join方法可以使主線程停止知道子執行緒執行完畢。具體怎麼實...

MySQL中的幾種join總結

an highlighted block join 建表語句 drop database if exists test create database test use test 左表t1 drop table if exists t1 create table t1 id int not null...