mysql之连接查询,多表连接

连接查询,又称为多表查询,当查询的字段来自多个表的时候就需要连接查询。

一 笛卡尔乘积

定义: 笛卡尔乘积是指在数学中,两个集合XY的笛卡尔积(Cartesian product),又称直积,表示为X × Y,第一个对象是X的成员而第二个对象是Y的所有可能有序对的其中一个成员。

在mysql中的笛卡尔乘积现象:A表有n行,B表有m行,查询结果为n*m行。

二 连接查询

我们这里只记录sql99标准的句法

select 查询列表
from 表1 【别名】
【连接类型】join 表2 【别名】
on 连接条件
【where 筛选条件】【group by 分组条件】【order by 排序类型】

1. 内连接 inner join

1) 等值连接

#案例1:查询员工名,部门名
select last_name,department_name from employees e inner join departments d on e.department_id=d.department_id;
#案例2:查询名字中包含e的员工名和工种名(筛选)
select last_name,job_title from employees e inner join jobs j on e.job_id=j.job_id where last_name like '%e%';
#案例3:查询部门个数大于3的城市名和部门个数(分组+筛选)
select city,count(*) from departments d inner join locations l on d.location_id=l.location_id group by city having count(*)>3;
#案例4:查询部门的员工个数大于3的部门名和员工个数,并按个数降序(添加排序)
select department_name,count(*) 员工个数 from employees e inner join departments d on e.department_id=d.department_id group by d.department_id having count(*)>3 order by count(*) desc;
#案例5:查询员工名、部门名、工种名,并按部门名降序(三表连接)
select last_name,department_name,job_title from employees e inner join departments d on e.department_id=d.department_id inner join jobs j on e.job_id=j.job_id order by department_name desc;

2)非等值连接

#案例1
select e.salary, grade_level from employees e inner join job_grades g on e.salary between lowest_sal and highest_sal;
#案例2:查询员工个数大于20的工资级别,并且按工资级别降序排列
select grade_level,count(*) from employees inner join job_grades on salary between lowest_sal and highest_sal group by grade_level having count(*)>20;

3)自连接

#案例:查询姓名中包含字符k的员工的名字及其上级的名字
select e.last_name employeeName,m.last_name managerName from employees e inner join employees m on e.manager_id=m.employee_id where e.last_name like '%k%';

2. 外连接 【outer】join

外连接的应用场景:查询一个表有,另一个表没有的记录

外连接的查询结果包括主表中的所有记录。如果从表中有和它匹配的,则显示匹配的值,如果从表中没有匹配的,则显示null,外连接查询结果=内连接的查询结果+主表中有而从表中没有的记录。(left join 中左表是主表,right join中,右表是主表)。left join 和right join,如果交换两表的位置,可以实现同样的效果。

1) left join

#案例,left join查询哪个部门没有员工
select d.* from departments d left join employees e on d.department_id=e.department_id where e.department_id is null;

2)right join

#案例,right join查询哪个部门没有员工
select d.* from employees e right join departments d on e.department_id=d.department_id where e.department_id is null;

3)full join,mysql不支持

3. 交叉连接 cross join,其实就是笛卡尔乘积

发布了28 篇原创文章 · 获赞 0 · 访问量 1227

猜你喜欢

转载自blog.csdn.net/gaohanjie123/article/details/105415075
今日推荐