文章目录
sql中的易错点
where子句和having子句的区别
sql语句的执行过程
from --> (join)on --> where --> group by --> having --> select --> order by
区别
语句 | 声明 | 聚合函数 |
---|---|---|
where | 约束声明 | 不能使用 |
having | 过滤声明 | 可以使用 |
having 是对where查出的结果集再进行过滤
用法
只能使用where
价格大于100的商品名和数量
select goods_name,goods_number from sw_goods where goods_price > 100
//报错!!!因为前面并没有筛选出goods_price 字段
select goods_name,goods_number from sw_goods having goods_price > 100
直接对数据进行筛选
只能使用having
要查找平均工资大于3000的部门
select deptname, avg(salary) as sal from emp group by deptname having sal > 3000
//报错!!因为emp 这张数据表里面没有sal 这个字段
select deptname, avg(salary) as sal from emp where sal > 3000 group by deptname
//报错!!因为avg(salary)是聚合函数,emp 这张数据表里面没有avg(salary) 这个字段
select deptname, avg(salary) as sal from emp where avg(salary) > 3000 group by deptname
使用了聚合函数avg 且对结果集进行筛选
where和having都能使用
select goods_name,goods_price from sw_goods where goods_price > 100
select goods_name,goods_price from sw_goods having goods_price > 100
where直接对数据goods_price 字段筛选;having是对结果集再筛选,结果集中包含了goods_price
where和having一起使用
工资高于2000的员工所在部门平均工资高于3000的部门和平均工资
select deptname, avg(salary) as sal from emp where salary > 2000 group by deptname having sal > 3000
join中的on和where的区别
数据库在通过连接两张或多张表来返回结果时,都会生成一张中间的临时表,然后再将这张临时表返回给用户
当使用inner join时,功能与where完全相同,所以下面介绍left join
区别
- on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录
- where条件是在临时表生成后,再对临时表进行过滤的条件。
where后面:是先连接然生成临时查询结果,然后再筛选
on后面:先根据条件过滤筛选,再连 生成临时查询结果
举例
表1:tab1
id | size |
---|---|
1 | 10 |
2 | 20 |
3 | 30 |
表2:tab2
size | name |
---|---|
10 | AAA |
20 | BBB |
20 | CCC |
用where
select * form tab1 left join tab2 on (tab1.size = tab2.size) where tab2.name=’AAA’
执行过程:
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 |
用on
select * form tab1 left join tab2 on (tab1.size = tab2.size and tab2.name=’AAA’)
执行过程:
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 |