MySQL 内连接

396 阅读1分钟

内连接

  • 等值连接
  • 非等值连接
  • 自连接

数据表

员工表 部门表 地址表 工作表 工资级别 各种Join图示

内连接

  • 取两表交集部分
  • 语法
 select 查询列表
 from1 别名
 inner join2 别名
 on 连接条件

内连接inner可以省略

等值连接场景

案例一 查询员工名, 部门名

select last_name, department_name from employees e inner join departments d on e.department_id = d.department_id;

案例二 查询部门个数>3的城市名和部门个数

第一步 查询城市名和对应部门个数

select city, department_name from departments d inner join locations l on d.location_id = l.location_id

第二步 分组 要求是每个城市对应的部门个数 group by city

select city, count(*) from departments d inner join locations l on d.location_id = l.location_id group by city

非等值连接

案例一

查询员工的工资级别

select salary, grade_level from employees e inner join job_grades j on e.salary between  j.lowest_sal and j.highest_sal

自连接

案例一

查询员工名和上级名字

select a.last_name, b.last_name from employees a inner join employees b on a.manager_id = b.employee_id;