• MSSQL编程笔记三 left join on 和 left join where区别


    今天遇到用left join时候发现查询出来的结果比预期的少了很多?不知道为什么,上网一查,原来如此!

         在使用left join时,onwhere条件的区别如下:

    1 on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录。

    可以理解为,左表记录保留,右表不满足条件的填写为null

    2where条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有left join的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉。

          假设有两张表:

    1 tab1

    id size

    1 10

    2 20

    3 30

    2 tab2

    size name

    10 AAA

    20 BBB

    20 CCC


    两条SQL:
    1
    select * form tab1left join tab2 on (tab1.size = tab2.size) where tab2.name=’AAA’
    2
    select * form tab1left join tab2 on (tab1.size = tab2.size and tab2.name=’AAA’)

    第一条SQL的过程:

    1、中间表
    on
    条件
    tab1.size = tab2.size

    tab1.id   tab1.size    tab2.size     tab2.name

    1              10                  10              AAA

    2             20                    20             BBB

    2            20                     20              CCC

    3            30                   (null)             (null)

    2、再对中间表过滤
    where
    条件:
    tab2.name=’AAA’

    tab1.id      tab1.size       tab2.size     tab2.name

    1                 10                 10             AAA

    第二条SQL的过程:

    1、中间表
    on
    条件
    tab1.size = tab2.size and tab2.name=’AAA’
    (
    条件不为真也会返回左表中的记录)

    tab1.id     tab1.size        tab2.size       tab2.name

    1              10                    10                  AAA

    2              20                  (null)              (null)

    3              30                  (null)                (null)

        其实以上结果的关键原因就是leftjoin,right join,full join的特殊性,不管on上的条件是否为真都会返回leftright表中的记录full则具有leftright的特性的并集。inner jion没这个特殊性,则条件放在on中和where中,返回的结果集是相同的。

  • 相关阅读:
    1058 A+B in Hogwarts (20)
    1046 Shortest Distance (20)
    1061 Dating (20)
    1041 Be Unique (20)
    1015 Reversible Primes (20)(20 分)
    pat 1027 Colors in Mars (20)
    PAT 1008 Elevator (20)
    操作系统 死锁
    Ajax的get方式传值 避免& 与= 号
    让IE浏览器支持CSS3表现
  • 原文地址:https://www.cnblogs.com/xiepeixing/p/2583956.html
Copyright © 2020-2023  润新知