码迷,mamicode.com
首页 > 其他好文 > 详细

l?e?f?t? ?j?o?i?n? ?o?n? ?a?n?d?与?l?e?f?t? ?j?o?i?n? ?o?n? ?w?h?e?r?e?的?区?别(转载)

时间:2014-05-08 17:37:34      阅读:320      评论:0      收藏:0      [点我收藏+]

标签:strong   c   2014   数据   使用   404   

数据库在通过连接两张或多张表来返回记录时,都会生成一张中间的临时表,然后再将这张临时表返回给用户。

在使用left jion时,on和where条件的区别如下:

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

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 tab1 left join tab2 on (tab1.size = tab2.size) where tab2.name=’AAA’
2、select * form tab1 left 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)

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


我的实验

select count(*) from T_EXPERT expert0_ left outer join T_GENERAL_REVIEWER generalrev1_ on expert0_.C_ID=generalrev1_.C_REVIEWER_ID and (generalrev1_.C_YEAR=2014);  --共140659条数据

 select count(*) from t_general_reviewer where c_year = 2014; --共121255条数据

select count(*) from t_expert where c_id not in (select c_reviewer_id from t_general_reviewer group by c_reviewer_id,c_year having c_year = 2014); --共19404条数据

19404+121255 = 140659条数据

分析如下:

执行第一条语句时,首先是查出了满足条件二的数据,不满足条件二的reviewer_id(即expert中的id)也会查出来,只是对应表t_general_reviewer中的字段显示为空

 

 

l?e?f?t? ?j?o?i?n? ?o?n? ?a?n?d?与?l?e?f?t? ?j?o?i?n? ?o?n? ?w?h?e?r?e?的?区?别(转载),码迷,mamicode.com

l?e?f?t? ?j?o?i?n? ?o?n? ?a?n?d?与?l?e?f?t? ?j?o?i?n? ?o?n? ?w?h?e?r?e?的?区?别(转载)

标签:strong   c   2014   数据   使用   404   

原文地址:http://www.cnblogs.com/maowh/p/3715752.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!