Python学习第二十五课——Mysql (多表查询)

时间:2023-12-21 19:26:32

多表查询:

内连接查询:

首先:创建两个表一个为tableA,一个为tableB,并且插入数据(代码省略)

Python学习第二十五课——Mysql (多表查询)

同时查询两个表的记录:

select * from tableA,tableB;

Python学习第二十五课——Mysql (多表查询)

根据tableA中id 等于 tableB 中refer_id 进行内连接查询:

select * from tableA,tableB where tableA.id=tableB.refer_id;

Python学习第二十五课——Mysql (多表查询)

也可以用一下方法进行内连接查询:

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;

Python学习第二十五课——Mysql (多表查询)

Python学习第二十五课——Mysql (多表查询)

具体例子(员工和部门):

首先:创建两个表一个为employee,一个为department,并且插入数据(代码省略)

Python学习第二十五课——Mysql (多表查询)

要求:根据员工表中的部门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 中 顺序无所谓

Python学习第二十五课——Mysql (多表查询)

外连接:

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 那个表 就以那个表为主 就是 显示那个表

Python学习第二十五课——Mysql (多表查询)

练习1:显示技术部的人和部门

select employee.name,department.dept_name from employee
inner join department
on department.dept_id=employee.dept_id
and department.dept_id=201;

Python学习第二十五课——Mysql (多表查询)

练习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 去重

Python学习第二十五课——Mysql (多表查询)