淺談外串連中的on條件字句

來源:互聯網
上載者:User

         在簡單的項目中使用的一般就是內串連,但是在實際系統級項目中外串連就很常見了。在外串連的使用中,本人發現有一個很多人都弄不清楚的問題,關於外串連中on的帶值條件字句的作用。

         當在內串連查詢中加入條件是,無論是將它加入到join子句,還是加入到where子句,其效果是完全一樣的,但對於外串連情況就不同了。當把條件加入到join子句時,SQL Server、Informix會返回外串連表的全部行,然後使用指定的條件返回第二個表的行。如果將條件放到where子句中,SQL Server將會首先進行串連操作,然後使用where子句對串連後的行進行篩選。下面的兩個查詢展示了條件放置位子對執行結果的影響:

條件在join子句:
select *
from    t_institution i
left outer join t_teller t
on i.inst_no = t.inst_no
and i.inst_no = “5801”
結果是:
inst_no      inst_name              inst_no      teller_no    teller_name
5801         天河區                 5801         0001         tom
5801         天河區                 5801         0002         david
5802         越秀區
5803         白雲區

條件在where子句:
select *
from    t_institution i
left outer join t_teller t
on i.inst_no = t.inst_no
where i.inst_no = “5801”
結果是:
inst_no      inst_name              inst_no      teller_no    teller_name
5801         天河區                 5801         0001         tom
5801         天河區                 5801         0002         david


    所以,在外串連中,on裡的屬性等於具體值的條件,當涉及到的屬性是主表的時候,這個條件其實無法發揮篩選作用的。

    或者用一種方式精確表達,對於外串連+on條件情況時,先用on裡的條件式篩選,再補on中條件中篩選掉的主表裡的屬性。(不懂的話可以看我的另一篇文章:sql語句執行順序)

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.