06MySQL分页查询子查询经典案例联合查询
Posted shawnyue-08
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了06MySQL分页查询子查询经典案例联合查询相关的知识,希望对你有一定的参考价值。
分页查询
#进阶九、分页查询
/*
应用场景:当要显示的数据一页显示不全时,需要分页提交sql请求。
语法:
select 查询列表
from 表名
[连接类型] join 表2
on 连接条件
where 筛选条件
group by 分组条件
having 分组后的筛选
order by 排序
limit 起始索引offset,显示的条目数size;
注意:在学习字符串的substring函数时,字符串的索引从1开始,但是在这里,起始索引offset从0开始
1、特点:limit子句在查询语句的最后,
2、要显示页数是page,每一页的条目数是size,limit (page-1)*size,size
*/
#查询前5条员工的信息
SELECT *
FROM employees
LIMIT 0,5;
SELECT *
FROM employees
LIMIT 5;
#查询第11条到第25条
SELECT *
FROM employees
LIMIT 10,15
#有奖金的员工信息,工资较高的前10名
SELECT *
FROM employees
WHERE commission_pct IS NOT NULL
ORDER BY salary DESC
LIMIT 10;
子查询经典案例
#1、查询工资最低的员工信息
SELECT *
FROM employees
WHERE salary = (
SELECT MIN(salary)
FROM employees
);
#2、查询平均工资最低的部门信息 ※
SELECT d.*
FROM (
SELECT AVG(salary) 平均工资, department_id
FROM employees
GROUP BY department_id
) temp
INNER JOIN departments d
ON temp.department_id = d.`department_id`
ORDER BY 平均工资 ASC
LIMIT 1;
#3、查询平均工资最低的部门信息和该部门的平均工资
SELECT 平均工资, d.*
FROM (
SELECT AVG(salary) 平均工资, department_id
FROM employees
GROUP BY department_id
) temp
INNER JOIN departments d
ON temp.department_id = d.`department_id`
ORDER BY 平均工资 ASC
LIMIT 1;
#4、查询平均工资最高的job信息
SELECT temp.平均工资, j.*
FROM (
SELECT AVG(salary) 平均工资, job_id
FROM employees
GROUP BY job_id
ORDER BY 平均工资 DESC
LIMIT 1
) temp
INNER JOIN jobs j
ON temp.job_id = j.`job_id`;
#5、查询平均工资高于公司平均工资的部门有哪些?
SELECT department_id, AVG(salary) 平均工资
FROM employees
GROUP BY department_id
HAVING 平均工资 > (
SELECT AVG(salary) 公司平均工资
FROM employees
);
#6、查询公司中所有manager的详细信息
SELECT *
FROM employees
WHERE employee_id IN (
SELECT manager_id
FROM employees
GROUP BY manager_id
);
#7、各个部门的最高工资中,最低的那个是多少?
SELECT MIN(temp.最高工资) 最低工资
FROM (
SELECT MAX(salary) 最高工资
FROM employees
GROUP BY department_id
) temp;
#并且查询是那个部门
SELECT department_id, MAX(salary)
FROM employees
GROUP BY department_id
HAVING MAX(salary) = (
SELECT MAX(salary) maxSalary
FROM employees
GROUP BY department_id
ORDER BY maxSalary ASC
LIMIT 1
);
#8、查询平均工资最高的部门 的manager的详细信息,last_name,department_id,email,salary
SELECT last_name, e.department_id, email, salary
FROM employees e
WHERE employee_id = (
SELECT d.`manager_id`
FROM (
SELECT AVG(salary) maxSalary, department_id
FROM employees
GROUP BY department_id
ORDER BY maxSalary DESC
LIMIT 1
) temp
JOIN departments d
ON temp.department_id = d.`department_id`
);
联合查询
#进阶十、联合查询
/*
union:将多条查询语句的结果合并为一个结果,
语法:
查询语句1
union
查询语句2
*/
#查询部门编号>90或者是邮箱中包含a的员工信息
SELECT *
FROM employees
WHERE department_id > 90 OR email LIKE ‘%a%‘;
或者
SELECT * FROM employees WHERE department_id > 90
UNION
SELECT * FROM employees WHERE email LIKE ‘%a%‘;
/*
当我们要查询的结果来自多张表,而且多张表之间没有连接关系,查询的信息(字段)一致时,可以使用联合查询
*/
/*
联合查询的特点:
1、要求多条查询语句的查询列数一致;
2、要求多条查询语句的每一列的类型和顺序最好一致;
3、union关键字默认是去重的,使用union all可以包含重复项
*/
以上是关于06MySQL分页查询子查询经典案例联合查询的主要内容,如果未能解决你的问题,请参考以下文章