mysql-多表查询
#多表查询语法 select 字段1,字段2... from 表1,表2... [where 条件]
注意: 如果不加条件直接进行查询,则会出现以下效果,这种结果我们称之为 笛卡尔乘积
#查询人员和部门所有信息 select * from person,dept
笛卡尔乘积公式 : A表中数据条数 * B表中数据条数 = 笛卡尔乘积.
笛卡尔乘积示例
#查询人员和部门所有信息 select * from person,dept where person.did = dept.did;
#注意: 多表查询时,一定要找到两个表中相互关联的字段,并且作为条件使用
多表链接查询
|
1
2
3
4
|
#多表连接查询语法(重点)SELECT 字段列表 FROM 表1 INNER|LEFT|RIGHT JOIN 表2ON 表1.字段 = 表2.字段; |
1 内连接查询 (只显示符合条件的数据)
|
1
2
|
#查询人员和部门所有信息select * from person inner join dept on person.did =dept.did; |
效果: 大家可能会发现, 内连接查询与多表联合查询的效果是一样的.

示例2 左外连接查询 (左边表中的数据优先全部显示)
|
1
2
|
#查询人员和部门所有信息select * from person left join dept on person.did =dept.did; |
效果:人员表中的数据全部都显示,而 部门表中的数据符合条件的才会显示,不符合条件的会以 null 进行填充.

示例3 右外连接查询 (右边表中的数据优先全部显示)
|
1
2
|
#查询人员和部门所有信息select * from person right join dept on person.did =dept.did; |
效果:正好与[左外连接相反]
示例4 全连接查询(显示左右表中全部数据)
全连接查询:是在内连接的基础上增加 左右两边没有显示的数据
注意: mysql并不支持全连接 full JOIN 关键字
注意: 但是mysql 提供了 UNION 关键字.使用 UNION 可以间接实现 full JOIN 功能
|
1
2
3
4
5
|
#查询人员和部门的所有数据 SELECT * FROM person LEFT JOIN dept ON person.did = dept.didUNIONSELECT * FROM person RIGHT JOIN dept ON person.did = dept.did |
1. 查询出 教学部 年龄大于20岁,并且工资小于40000的员工,按工资倒序排列.(要求:分别使用多表联合查询和内连接查询)
select * from person P,dept d where person.did = dept.did
and d.dname="python"
and salary<4000
and age>20
ORDER BY salary DESC;
#1.多表联合查询方式:
select * from person p1,dept d2 where p1.did = d2.did
and d2.dname='python'
and age>20
and salary <40000
ORDER BY salary DESC;
#2.内连接查询方式:
SELECT * FROM person p1 INNER JOIN dept d2 ON p1.did= d2.did
and d2.dname='python'
and age>20
and salary <40000
ORDER BY salary DESC;
2.查询每个部门中最高工资和最低工资是多少,显示部门名称
select max(salary),min(salary),dept.dname fromperson left join dept where person.did=dept.did
GROUP BY person.did;
select MAX(salary),MIN(salary),dept.dname from
person LEFT JOIN dept
ON person.did = dept.did
GROUP BY person.did;


浙公网安备 33010602011771号