8.连接查询 -- SQL99标准
1.SQL99连接查询语法
1 select查询列表 2 from表1别名 3 连接类型 join 表2 4 on 连接条件 5 [where筛选条件] 6 [groupby分组] 7 [having 筛选条件] 8 [order by排序列表]
2.连接类型
1 连接分类: 2 内连接: inner 3 外链接: 4 左外链接: left outer 5 右外链接: right outer 6 全外链接: full outer(mysql不支持) 7 交叉连接: cross
3.内连接
1 # 语法规则: 2 select查询列表 3 from biao1 别名 4 on 连接条件;
(1).等值连接
1 # 案例1: 查询员工名, 部门名 2 select last_name, department_name 3 from employees as e 4 inner join departments as d 5 on e.department_id = d.department_id;
6 # 案例2: 查询名字中包含e的员工名和工种名(添加筛选) 7 select last_name, job_title 8 from employees as e 9 inner join jobs as j 10 on e.job_id = j.job_id 11 where e.last_name like '%e%';
12 # 案例3: 查询部门个数>3的城市名和部门个数(添加分组和筛选) 13 select city, count(*) 14 from locations as l 15 inner join departments as d 16 on l.location_id=d.location_id 17 groupby city 18 having count(*)>3;
19 # 案例4: 查询部门员工个数大于3的部门名和员工个数, 并按个数降序. 20 select department_name, count(*) 21 from departments as d 22 inner join employees as e 23 on d.department_id=e.department_id 24 groupby department_name 25 having count(*)>3 26 order by count(*) desc;
27 # 5.查询员工名, 部门名, 工种名, 并按部门名降序 28 select last_name, department_name, job_title 29 from emlpoyees as e 30 inner join departments as d on e.department_id = d.department_id 31 inner join jobs as j on e.job_id=j.job_id 32 order by j.job_title desc; 33 (注:三张表连接时,必须保证第一张表,即from后的表能够分别与join后面的表连接)
(2).非等值连接
1 # 查询员工的工资级别 2 select salary, grade_level 3 from employees as e 4 inner join job_grades as g 5 on e.salary between g.lowest_sal and g.heighest_sal;
(3).自连接
1 # 查询员工的名字, 上级凌达的名字 2 select e.last_name, m.last_name 3 from employees as e 4 join employees m 5 on e.manager_id = m.employee_id;
4.外链接
1 # 1.应用场景: 用于查询一个表中有, 另一个表里没有的记录
2 # 2.特点: 3 1).外链接的查询结果为主表的所有记录 4 如果从表中有和它匹配的,则显示匹配的值 5 如果从表中没有和它匹配的,则显示null 6 外表连接查询结果=内连接结果+主表中有而从表没有的记录 7 2).左外连接, left join左边的是左表 8 右外连接, right join右边的是主表 9 3).左外连接和右外连接交换两个表的顺序,同时更改对应的连接方式,只要保证主表不变,可以实现同样的效果 10 4).全外连接=内连接的结果+表1有表2没有的+表2中有表1没有的
1 # 左外连接案例:查询哪个部门没有员工 2 select d.*, e.employee_id 3 from departments as d 4 left outer join employees as e 5 on d.department_id = e.department_id 6 where e.employee_id isnull;
1 # 右外连接实现上面的查询 2 SELECT department_name,employee_id 3 FROM employees AS e 4 RIGHT OUTER JOIN departments AS d 5 ON e.department_id=d.department_id 6 WHERE e.department_id IS NULL;
浙公网安备 33010602011771号