sql語句中left join、inner join中的on與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語句3:select a.*, b.* from a left join b on a.id = b.id and b.class = 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

sql語句3的執行結果爲:

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

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

1        1            1        1

2        1           

3        2           

由sql語句1可見,left join 中左表的全部記錄將全部被查詢顯示,on 後面的條件對它不起作用,除非再後面再加上where來進行篩選,這就是sql語句2了;由sql語句3可見,on後面的條件中,右表的限制條件將會起作用。

**********************************************************************************

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

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

sql語句6:select a.*, b.* from a, b where a.id = b.id and a.type = 1;

sql語句7:select a.*, b.* from a, b where a.type = 1 and a.id = b.id;

這四條語句的執行結果一樣,如下:

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

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

1        1            1        1

2        1            2        2

由此可見,inner join 中on後面的限制條件將全部起作用,這與where的執行結果是一樣的。另外,where語句與inner join確實能得到相同的結果,只是效率不同

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章