本教程中所使用的数据库的建表语句都在“SQL教程——索引”这篇文章中,点击链接直达:索引&建表语句
摘要:本文主要介绍SQL92标准的连接查询
连接查询
含义:又称多表查询,当查询的字段来自多个表时,就需要用到链接查询。
分类:按年代分类:
sq192标准:仅仅支持内连接
sq199标准:【推荐】:支持内连接+外连接(左外和右外)+交叉连接
功能分类:
内连接:
等值连接
非等值连接
自连接
外连接:
左外连接
右外连接
全外连接
交叉连接
一、SQL92标准
1、等值连接
-
多表等值连接的结果为多表的交集部分
-
n表连接,至少需要n-1个链接条件
-
多表的顺序没有要求
-
一般需要为表起别名
-
可以搭配前边介绍的所有字句使用,比如排序、分组、筛选
#案例1:查询女神名和对应的男神名
select name, boyName from boys, beauty where beauty.boyfriend_id = boys.id;
#案例2:查询员工名和对应的部门名
select last_name, department_name
from employees, departments
where employees.department_id = departments.department_id;
#案例3:查询员工名、工种号、工种名 要用别名就用别名,不能起了别名之后,where后还跟原名
select e.last_name, e.job_id, j.job_title
from jobs j, employees e
where e.job_id = j.job_id;
#添加筛选条件
#案例1:查询有奖金的员工名、部门名
select e.last_name, d.department_name, e.commission_pct
from employees e, departments d
where d.department_id = e.department_id
and e.commission_pct is not null;
#案例2:查询城市名中第二个字符为0的部门名和城市名
select department_name, city
from departments d, locations l
where d.location_id = l.location_id
and city like '_o%';
#添加分组
#案例1:查询每个城市的部门个数
select count(*) 个数, city
from departments d, locations l
where d.location_id = l.location_id
group by city;
#案例2:查询有奖金的每个部门的部门名和部门的领导编号和该部门的最低工资
select d.department_name, d.manager_id, min(e.salary)
from departments d, employees e
where d.department_id = e.department_id
and e.commission_pct is not null
group by d.department_id;
#案例3:查询每个工种的工种名和员工的个数,并且按员工的个数排序
select job_title, count(*) 人数
from employees e, jobs j
where j.job_id = e.job_id
group by e.job_id
order by count(*) desc;
#三表连接
#案例:查询员工名、部门名和所在的城市
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;
2、非等值连接
#案例1:查询员工的工资和工资级别
select salary, grade_level
from employees e, job_grades
where salary between lowest_sal and highest_sal;
3、自连接
#案例1:查询员工名和上级的名称。
select e1.last_name, e2.last_name
from employees e1, employees e2
where e1.manager_id = e2.employee_id;
#Test1:查询每个工种、每个部门的部门名、工种名和最低工资
select department_name, job_title, min(salary)
from employees e, departments d, jobs j
where e.department_id = d.department_id
and e.job_id = j.job_id
group by e.job_id, d.department_id;
#Test2:查询每个国家下的部门个数大于2的国家编号
select country_id, count(*)
from departments d, locations l
where d.location_id = l.location_id
group by country_id
having count(*) > 2;
#Test3:选择指定员工的姓名,员工号,以及它的管理者的姓名和员工号,结果类似于下面的格式
employees Emp# manager Mgr#
kochhar 101 king 100
select e.last_name employees, e.employee_id 'Emp#', m.last_name manager, m.employee_id
from employees e, employees m
where e.manager_id = m.employee_id;