数据库在通过连接两张或多张表来返回记录时,都会生成一张中间的临时表,然后再将这张临时表返回给用户。
在使用left jion时,on和where条件的区别如下:
1、 on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录。
2、where条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有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上的条件是否为真都会返回left或right表中的记录,full则具有left和right的特性的并集。 而inner jion没这个特殊性,则条件放在on中和where中,返回的结果集是相同的。
我的使用案例:
提取南昌二七王游戏每日在线时长在2小时的玩家信息排行榜
select distinct t.UserID as 用户ID,t.Nick as 用户昵称,ISNULL(t.todayPlayTime,0)-ISNULL(p.previousPlayTime,0) as 当日在线时长,t.pddate as 日期 from
(select distinct a.UserID,c.Nick,a.PlayTimeCount as todayPlayTime,CONVERT(varchar(10),a.CreateTime,120) as pddate from UserServerInfos a, UserAccounts c where a.DatabaseName='GYpkerqiwangbs20100507DB' and c.userid=a.userid and CONVERT(varchar(10),a.CreateTime,120)=convert(varchar(10),getdate()-1,120) and CONVERT(varchar(10),c.CreateTime,120)=convert(varchar(10),getdate()-1,120) ) t
left join
(select distinct a.UserID,c.Nick,a.PlayTimeCount as previousPlayTime,CONVERT(varchar(10),a.CreateTime,120) as yqdate from UserServerInfos a, UserAccounts c where a.DatabaseName='GYpkerqiwangbs20100507DB' and c.userid=a.userid and CONVERT(varchar(10),a.CreateTime,120)=convert(varchar(10),getdate()-2,120) and CONVERT(varchar(10),c.CreateTime,120)=convert(varchar(10),getdate()-2,120) ) p
on (t.userid=p.userid and ISNULL(t.todayPlayTime,0)-ISNULL(p.previousPlayTime,0)>7200) order by 当日在线时长 desc
t代表昨天的数据 p代表前天的数据
用left join 保证一定取到所有的数据,因为昨天可能有前天新来的游戏玩家,所以不能用inner join取交集。
每日在线时长在2小时 on (t.userid=p.userid and ISNULL(t.todayPlayTime,0)-ISNULL(p.previousPlayTime,0)>7200)
on 的写法比较关键,以前不知道怎么写。