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 = 2;
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???????????????????
2??????? 1???????????????????
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 后面的條件再做一次篩選,因為在原來的結果集中沒有與a.type =2 關聯得到的b表中的值,所以這時候b表的數據就都不顯示
sql語句2中,加了where條件,就先過濾where條件中的值;由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確實能得到相同的結果,只是效率不同(這個我沒有測試過,不過我相信這個結論)。
但是sql語句6是否比sql語句7的效率要低一些,我沒有足夠的數據量來測試,不過我也相信是如此的。
?
本文來自CSDN博客,轉載請標明出處: http://blog.csdn.net/winter3125/archive/2009/12/18/5032871.aspx
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
