SQL连接查询案例
(一)等值連接(sql92語法)
1.簡單的兩表連接
案例1:查詢員工名和對應的部門名
SELECT last_name,department_name from employees e,departments d WHERE e.department_id = d.department_id為表起別名:
① 提高語句的簡潔度
② 區(qū)分多個重名的字段
注意:如果為表起了別名,則查詢的字段就不能使用原來的表名去限定
2.添加篩選條件
案例1:查詢部門編號>100的部門名和所在的城市名
SELECT department_name,city from departments d, locations l WHERE d.location_id = l.location_id and d.department_id>100案例2: 查詢有獎金的員工名、部門名
SELECT last_name,department_name from employees e,departments d WHERE e.commission_pct is not null and e.department_id=d.department_id案例3:查詢城市命中第二個字符為o的部門名和城市名
SELECT department_name,city from departments d,locations l where d.location_id = l.location_id and city like "_o%"3. 添加分組+篩選
案例1:查詢每個城市的部門個數(shù)
SELECT city,COUNT(*) from departments d, locations l WHERE d.location_id=l.location_id GROUP BY l.city案例2:查詢有獎金的每個部門的部門名和部門的領(lǐng)導編號和該部門的最低工資
select d.department_name,d.manager_id,MIN(e.salary) from employees e,departments d where e.department_id=d.department_id and e.commission_pct is not null GROUP BY d.department_id案例3:查詢部門中員工個數(shù)>10的部門名
SELECT department_name,COUNT(*) from departments d,employees e where e.department_id=d.department_id GROUP BY d.department_id HAVING COUNT(*)>104. 添加分組、刪選、排序
案例:查詢哪個部門的員工個數(shù)>5,并按員工個數(shù)進行降序
SELECT department_name,COUNT(*) from departments d,employees e where d.department_id=e.department_id GROUP BY d.department_id HAVING COUNT(*)>5 ORDER BY COUNT(*) DESC5.三表查詢
案例:查詢員工名、部門名和所在的城市
SELECT last_name,department_name,city FROM employees e,departments d,locations l WHERE e.`department_id`=d.`department_id` AND d.`location_id`=l.`location_id` AND city LIKE 's%' ORDER BY department_name DESC;SQL99語法內(nèi)連接
select 查詢列表
from 表名1 別名
【inner】 join 表名2 別名
on 連接條件
where 篩選條件
group by 分組列表
having 分組后篩選
order by 排序列表
sql92和sql99的區(qū)別
sql99,使用join關(guān)鍵字代替了之前的逗號,并且將連接條件和篩選條件進行了分離,提高閱讀性
(二)非等值連接
案例:查詢部門編號在10-90之間的員工的工資級別,并按級別進行分組
SELECT j.grade_level,count(*) from employees e join job_grades j on e.salary BETWEEN j.lowest_sal and j.highest_sal where e.department_id BETWEEN 10 and 90 GROUP BY j.grade_level(三)自連接
案例:查詢員工名和對應的領(lǐng)導名
select e1.last_name as 員工,e2.last_name as 領(lǐng)導 from employees e1 join employees e2 on e1.manager_id = e2.employee_id(四)外連接(sql99語法)
應用場景
用于查詢一個表中有,另一個表沒有的記錄
特點
如果從表中有和它匹配的,則顯示匹配的值
如果從表中沒有和它匹配的,則顯示null
外連接查詢結(jié)果=內(nèi)連接結(jié)果+主表中有而從表沒有的記錄
右外連接,right join右邊的是主表
語法
select 查詢列表
from 表1 別名
left | right outer join 表2 別名
on 連接條件
where 篩選條件
表結(jié)構(gòu)
數(shù)據(jù):girls.sql
beauty表
boys表
案例1: 查詢所有女神記錄,以及對應的男神名,如果沒有對應的男神,則顯示為null
左連接:
SELECT b.*,bo.* from beauty b LEFT JOIN boys bo on b.boyfriend_id=bo.id案例2: 哪個女神沒有男朋友
左連接
SELECT b.name from beauty b LEFT JOIN boys bo on b.boyfriend_id=bo.id WHERE bo.id is null案例3:查詢哪個部門沒有員工,并顯示其部門編號和部門名
SELECT d.department_id,d.department_name from departments d LEFT JOIN employees e on d.department_id=e.department_id where e.employee_id is null總結(jié)
- 上一篇: SQL分组查询案例
- 下一篇: Pipenv管理Python虚拟环境