文章目錄
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 |