使用子查询(嵌套查询)
概念:一个select语句中嵌套了另外的一个或者多个select语句。
#查询工资比Simth工资高的员工信息
SELECT
a.last_name,
a.salary
FROM s_emp a
WHERE salary > (
SELECT salary
FROM s_emp b
WHERE b.last_name = 'Smith'
);
#查询平均工资比41号部门的平均工资高的部门中员工的信息
SELECT
a.last_name,
a.salary,
a.dept_id
FROM
s_emp a
WHERE a.dept_id IN (
SELECT b.dept_id
FROM s_emp b
GROUP BY b.dept_id
HAVING avg(b.salary) > (
SELECT avg(c.salary)
FROM s_emp c
WHERE c.dept_id = 41
)
);
组合查询
概念:如果有俩条sql语句,每一条sql都可以查询出一个结果,这个被称之为结果集。MySQL也允许执行多个查询(多条SELECT语句),并将结果集作为单个查询结果集返回 。这个操作称为组合查询。
语法规则:
Union
必须由两条或者两条以上的SELECT
语句组成,语句之间使用Union
链接- 俩个结果集中【查询的列】要完全一致。
union:查询结果集中自动去除了重复的行 。
union all:查询所有的结果集。
#查询员工号1 2 3 4的员工信息
select a.id from s_emp a where a.id in (1,2,3,4);
#查询员工号1 2 3 5的员工信息
select a.id from s_emp a where a.id in (1,2,3,5);
#并集操作 :重复数据显示一次
select a.id from s_emp a where a.id in (1,2,3,4)
union
select a.id from s_emp a where a.id in (1,2,3,5);
#把俩个结果集合在一起显示出来,重复全部显示,对结果集不做任何处理
select a.id from s_emp a where a.id in (1,2,3,4)
union all
select a.id from s_emp a where a.id in (1,2,3,5);
对组合查询结果排序
- 不允许使用多条ORDER BY子句
- 必须出现在最后一条SELECT语句之后
#对上述结果集进行排序,按照员工号进行降序
select a.id from s_emp a where a.id in (1,2,3,4)
union
select b.id from s_emp b where b.id in (1,2,3,5)
order by id desc;
不同表的组合查询
#查询员工号,部门号,区域号
select a.id from s_emp a
union all
select b.id from s_dept b
union all
select c.id from s_region c
#查询员工号,员工名称,部门号,部门名称,区域号,区域名称
select a.id,a.last_name as name from s_emp a
union all
select b.id,b.`name` from s_dept b
union all
select c.id,c.`name` from s_region c