on 和where 的区别
来源:互联网 发布:点歌台软件 编辑:程序博客网 时间:2024/05/06 21:42
今天做一个ajax 分页时,老是显示总页面与返回的记录数不对。仔细查了一下然来是SQL 语句有问题。
所以SQL 语句与执行结果如下:
mysql> select * from (select groupID ,count(*) as entityNumber from hxgroupentitycontainmenttab group by groupID) as t1 right join hxgroupentitytab as t2 on t1.groupID=t2.id and t2.name like '%group%';
可以看到aptech7不满足 理科%group%条件也返回过来了。这就是right join 的特性(返回右表所有记录) 。
把语句换成如下(on 改为了where以后)
mysql> select * from (select groupID ,count(*) as entityNumber from hxgroupentitycontainmenttab group by groupID) as t1 right join hxgroupentitytab as t2 on t1.groupID=t2.id where t2.name like '%group%';
执行结果如下:
此时结果符合项目要求。
下面对on 与where 区别总结一下:
SQL中on条件与where条件的区别
所以SQL 语句与执行结果如下:
mysql> select * from (select groupID ,count(*) as entityNumber from hxgroupentitycontainmenttab group by groupID) as t1 right join hxgroupentitytab as t2 on t1.groupID=t2.id and t2.name like '%group%';
可以看到aptech7不满足 理科%group%条件也返回过来了。这就是right join 的特性(返回右表所有记录) 。
把语句换成如下(on 改为了where以后)
mysql> select * from (select groupID ,count(*) as entityNumber from hxgroupentitycontainmenttab group by groupID) as t1 right join hxgroupentitytab as t2 on t1.groupID=t2.id where t2.name like '%group%';
执行结果如下:
此时结果符合项目要求。
下面对on 与where 区别总结一下:
SQL中on条件与where条件的区别
数据库在通过连接两张或多张表来返回记录时,都会生成一张中间的临时表,然后再将这张临时表返回给用户。
在使用left jion时,on和where条件的区别如下:
1、 on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录。
2、where条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有left join的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉。
假设有两张表:
表1:tab2
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.sizetab1.idtab1.sizetab2.sizetab2.name
1
10
10
AAA
2
20
20
BBB
2
20
20
CCC
3
30
(null)
(null)
|
|
2、再对中间表过滤
where 条件:
tab2.name=’AAA’
1
10
10
AAA
第二条SQL的过程:
1、中间表on条件:
tab1.size = tab2.size and tab2.name=’AAA’
(条件不为真也会返回左表中的记录)tab1.idtab1.sizetab2.sizetab2.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中,返回的结果集是相同的。
- on 和where 的区别
- on和where的区别
- where 和 on 的区别
- on和where的区别
- on和where的区别
- sql where 和on 的区别
- SQL中ON和WHERE的区别
- SQL中ON和WHERE的区别
- sql 中on和where 的区别
- sql 的join on 和 where 区别
- join中on和where的区别
- inner join on 和 where 的区别
- where、having和on的区别
- sql中where和on的区别
- sql where 和on 的区别
- SQL中on和where的区别
- sql where和on的区别
- sql join 的on 和 where 区别
- 完全解读 margin 标签
- SHOP++ V1.0测试配置说明
- SHOP++源码部署说明:
- Android移植开发(1):源代码下载&环境搭建
- HTML5 API的威力
- on 和where 的区别
- windows 程序自启动
- cmd here
- C#.net 后台cs 调用前台javascript 的方法
- Android
- (转) Android的Window类
- 宿命轮回里的爱与恨
- ——大牛很通俗地介绍《信号与系统》
- android view/drawable引用无法取得