多表查询:
内连接查询:
首先:创建两个表一个为tableA,一个为tableB,并且插入数据(代码省略)
同时查询两个表的记录:
select * from tableA,tableB;
根据tableA中id 等于 tableB 中refer_id 进行内连接查询:
select * from tableA,tableB where tableA.id=tableB.refer_id;
也可以用一下方法进行内连接查询:
select * from tableB inner join tableA on tableB.refer_id=tableA.id; --inner join -- on --用法 select tableA.id,tableA.name,tableB.name from tableB inner join tableA on tableB.refer_id=tableA.id;
具体例子(员工和部门):
首先:创建两个表一个为employee,一个为department,并且插入数据(代码省略)
要求:根据员工表中的部门id 和 部门表中的部门id 对应查询出 员工所在部门;
select employee.name,department.dept_name from department
inner join employee
on department.dept_id=employee.dept_id; -- 内连接查询,此时from A inner join B 中 顺序无所谓
外连接:
select employee.name,department.dept_name from department
left join employee
on department.dept_id=employee.dept_id; -- from 那个表 就以那个表为主 就是 显示那个表 select employee.name,department.dept_name from employee
left join department
on department.dept_id=employee.dept_id; -- from 那个表 就以那个表为主 就是 显示那个表
练习1:显示技术部的人和部门
select employee.name,department.dept_name from employee
inner join department
on department.dept_id=employee.dept_id
and department.dept_id=201;
练习2:显示拥有大于25岁员工的部门(如有多个只显示一个即可)
select department.dept_name from department
inner join employee
on department.dept_id=employee.dept_id
and employee.age>25; select DISTINCT department.dept_name from department
inner join employee
on department.dept_id=employee.dept_id
and employee.age>25; -- DISTINCT 去重