当前位置:网站首页>MySQL - subquery usage
MySQL - subquery usage
2022-06-26 19:20:00 【Wan Li Gu Cheng】
List of articles
MySQL—— Subquery usage
1、 Overview of subquery
Introduction to subquery
Subquery refers to a query that is nested within another query statement by one query statement , Internal query is the condition of external query , This feature comes from MySQL4.1 Start introducing .
SQL The use of neutron queries has greatly enhanced SELECT The ability to query , Because many times queries need to get data from the result set , Or you need to calculate a data result from the same table first , Then with this data result ( It could be some scalar , It could also be a collection ) Compare .
Subquery basically uses
grammar :
SELECT -- Main query
select_list
FROM
table
WHERE
expr operator > (SELECT -- Subquery
select_list
FROM
table);
Subquery ( Internal query ) The execution is completed before the main query .
The results of the sub query are by the main query ( External query ) Use .
matters needing attention :
Subqueries should be enclosed in parentheses
Place the subquery to the right of the comparison criteria
Single line operators correspond to single line subqueries , Multiline operators correspond to multiline subqueries
Classification of subqueries
Return one or more records according to the results of sub query , Sub query is divided into single line sub query and multi line sub query .
Whether the sub query is executed more than once , Divide the subquery into related ( Or associated ) Subquery and unrelated ( Or unrelated ) Subquery .
2、 Use of subquery
2.1、 Single line sub query
Single line comparison operator
= be equal to ,> Greater than ,>= Greater than or equal to ,< Less than ,<= Less than or equal to ,<> It's not equal to
Using examples
-- Find employees whose salary is greater than the average salary of all employees
SELECT employee_id, first_name, last_name, salary
FROM employees
WHERE salary > (
SELECT AVG(salary) FROM employees);
-- Query salary greater than 149 Information of the employee whose salary is No
select employee_id,last_name,salary
from employees
where salary > (
select salary from employees where employee_id = 149)
-- return job_id And 141 Same as employee No ,salary Than 143 The name of the employee with a large number of employees ,job _id And wages
select last_name,job_id,salary
from employees
where job_id = (
select job_id from employees where employee_id = 141
)
and salary > (
select salary from employees where employee_id = 143
);
-- Return to the lowest paid employees of the company last_name,job_id and salary
select last_name,job_id,salary
from employees
where salary = (
select min(salary) from employees
);
-- Query and 147 Of employee No manager_id and department_id Of the same other employees employee_id,manager_id,department_id
select employee_id,manager_id,department_id
from employees
where manager_id = (
select manager_id from employees where employee_id = 147
)
and department_id = (
select department_id from employees where employee_id = 147
)
and employee_id <> 147;
-- The minimum wage is greater than 50 The Department of minimum wage id And its minimum wage
select department_id,min(salary) min_salary
from employees
where department_id is not null
group by department_id
having min_salary > (
select min(salary) from employees where department_id = 50
);
2.2、 Multi line sub query
Multi row subquery comparison operator

Using examples
-- Find the location that belongs to ID by 1700 All employees
SELECT
employee_id, first_name, last_name
FROM
employees
WHERE
department_id IN (SELECT
department_id
FROM
departments
WHERE
location_id = 1700)
ORDER BY first_name , last_name;
-- Return to other job id Middle ratio job id by 'IT_PROG’ Employee number and name of any low paid employee in the Department 、job id as well as salary
select last_name,job_id,salary
from employees
where salary < any (
select salary from employees where job_id = 'IT_PROG'
)
and job_id <> 'IT_PROG';
-- Return to other job id Middle ratio job id by 'IT_PROG’ Employee number and name of all low paid employees in the Department 、job id as well as salary
select last_name,job_id,salary
from employees
where salary < all (
select salary from employees where job_id = 'IT_PROG'
)
and job_id <> 'IT_PROG';
-- Query the Department with the lowest average wage ID
-- Mode one :
select department_id,avg(salary) from employees group by department_id order by avg(salary) limit 1;
-- Mode two :
select department_id
from employees
group by department_id
having avg(salary) = (
select min(avg_sal)
from (
select avg(salary) avg_sal from employees group by department_id
) t_dept_avg_sal
)
-- Mode three :
select department_id
from employees
group by department_id
having avg(salary) <= all (
select avg(salary) from employees group by department_id
);
-- Query the employee information of the leader in the employee table
select employee_id,last_name,manager_id
from employees
where employee_id in (
select manager_id from employees
);
-- Query the information of employees who are not leaders in the employee table
select employee_id,last_name,manager_id
from employees
where employee_id not in (
select manager_id from employees where manager_id is not null
);
2.3、 Correlation subquery
If the execution of a subquery depends on an external query , Usually, it is because the tables in the subquery use external tables , Conditional correlation is carried out , So every time you execute an external query , All subqueries have to be recalculated , Such a subquery is called an associated subquery .
Related sub queries are executed row by row , Each row of the main query executes a subquery .
Using examples
-- Query the salary of employees whose salary is greater than the average salary of the Department last_name, salary And its department_id
-- Mode one
select last_name,salary,department_id
from employees e1
where salary > (
select avg(salary) from employees e2 where e1.department_id = e2.department_id
);
-- Mode two
select last_name,salary,e.department_id
from employees e ,(select department_id,avg(salary) avg_sal from employees group by department_id) t_dept_avg_sal
where e.department_id = t_dept_avg_sal.department_id
and e.salary > t_dept_avg_sal.avg_sal;
-- Check the employee's id,salary, according to department_name Sort
select employee_id,salary
from employees e
order by (
select department_name from departments d where e.department_id = d.department_id
);
EXISTS And NOT EXISTS
EXISTS Operator is used to specify whether there are qualified rows in the subquery ,
If the subquery contains any rows , be EXISTS Operator return true. Otherwise it returns false.
EXISTS Operator terminates query processing immediately after a row is found , therefore , You can use EXISTS Operator to improve query performance
NOT EXISTS If there is no certain condition , Then return to true, Otherwise return to true.
Using examples :
-- Find manager's id, full name , Work and department id
select employee_id,last_name,job_id,department_id
from employees e1
where exists(
select * from employees e2 where e1.employee_id = e2.manager_id
)
-- Inquire about departments In the table , There is no in employees Of the departments in the table department_id and department_name
-- Mode one
select department_id,department_name
from departments d
where not exists(
select * from employees e where d.department_id = e.department_id
);
-- Mode two
select d.department_id,department_name
from departments d left join employees e on d.department_id = e.department_id
where e.department_id is null;
Subquery exercises
#1. Query and Zlotkey Name and salary of employees in the same department
select last_name,salary
from employees
where department_id in (
select department_id from employees where last_name = 'Zlotkey'
)
and last_name <> 'Zlotkey';
#2. Query the employee number of the employee whose salary is higher than the average salary of the company , Name and salary .
select employee_id,last_name,salary
from employees
where salary > (
select avg(salary) from employees
);
#3. Select salary greater than all JOB_ID = 'SA_MAN' The salary of the employee last_name,job_id, salary
select last_name,job_id,salary
from employees
where salary > (
select max(salary) from employees where job_id = 'SA_MAN'
);
#4. Queries and names contain letters u Employee number and name of employees in the same department
select employee_id,last_name
from employees
where department_id in (
select department_id from employees where last_name like '%u%'
);
#5. Check the... In the Department location_id by 1700 The employee number of the employee working in the Department
select employee_id
from employees e
where department_id in (
select department_id from departments where location_id = 1700
);
#6. The query manager is King The name and salary of the employee
select last_name,salary
from employees
where manager_id in (
select employee_id from employees where last_name = 'K_ing'
);
#7. Query the lowest paid employee information : last_name,salary
select last_name,salary
from employees
order by salary
limit 1;
select last_name,salary
from employees
where salary = (
select min(salary) from employees
);
#8. Search the Department with the lowest average wage
-- Mode one :
select * from departments
where department_id = (
select department_id
from employees
group by department_id
order by avg(salary)
limit 1
);
-- Mode two :
select * from departments
where department_id = (
select department_id
from employees
group by department_id
having avg(salary) = (
select min(avg_sal) from (select avg(salary) avg_sal from employees group by department_id) t_sal
)
);
-- Mode three :
select * from departments
where department_id = (
select department_id
from employees
group by department_id
having avg(salary) <= all (select avg(salary) from employees group by department_id)
);
#9. Query the information of the Department with the lowest average wage and the average wage of the Department , Subqueries can be written in the query field
select d.* ,(select avg(salary) from employees where department_id = d.department_id) avg_sal
from departments d
where department_id = (
select department_id
from employees
group by department_id
having avg(salary) <= all (select avg(salary) from employees group by department_id)
);
#10. Find the highest average wage job Information
-- Mode one :
select * from jobs
where job_id = (
select job_id
from employees
group by job_id
having avg(salary) >= all (
select avg(salary) from employees group by job_id )
);
-- Mode two :
select * from jobs
where job_id = (
select job_id
from employees
group by job_id
order by avg(salary) desc
limit 1
);
#11. Query the departments whose average salary is higher than the average salary of the company ?
select distinct department_id
from employees
where department_id is not null
group by department_id
having avg(salary) > (
select avg(salary) from employees
);
#12. Find out all the manager Details of
-- Mode one
select employee_id,last_name,salary,department_id
from employees e1
where exists(
select * from employees e2 where e1.employee_id = e2.manager_id
);
-- Mode two
select distinct man.employee_id,man.last_name,man.salary,man.department_id
from employees emp
join employees man
on emp.manager_id = man.employee_id ;
-- Mode three Subquery
select employee_id,last_name,salary,department_id
from employees
where employee_id in (
select distinct manager_id from employees
);
#13. Check the highest salary in each department What is the minimum wage of the lowest department
-- Mode one :
select department_id,min(salary) from employees
where department_id = (
select department_id from employees
group by department_id
having max(salary) = (
select min(max_sal)
from employees e, ( select max(salary) max_sal
from employees
where department_id is not null
group by department_id ) t_min_sal
));
-- Mode two :
select department_id,min(salary) from employees
where department_id = (
select department_id from employees
group by department_id
having max(salary) <= all (
select max(salary) from employees
group by department_id)
);
-- Mode three :
select min(salary) from employees
where department_id = (
select department_id from employees
group by department_id
having max(salary) = (
select max(salary) from employees
group by department_id
order by max(salary)
limit 1 )
);
-- Mode 4 :
select min(salary) from employees e,( select department_id, max(salary) from employees
group by department_id
order by max(salary)
limit 1) t_max_sal
where e.department_id = t_max_sal.department_id;
#14. Check the Department with the highest average wage manager Details of : last_name,department_id,email,salary
-- Mode one :
select last_name,department_id,email,salary
from employees
where employee_id = (
select manager_id
from departments
where department_id = (
select department_id from employees
group by department_id
order by avg(salary) desc
limit 1)
);
-- Mode two :
select last_name,department_id,email,salary
from employees
where employee_id = (
select manager_id from departments
where department_id = (
select department_id
from employees
group by department_id
having avg(salary) >= all (
select avg(salary)
from employees
where department_id is not null
group by department_id)
)
);
-- Mode three :
select last_name,department_id,email,salary from employees
where employee_id = (
select manager_id from departments
where department_id = (
select department_id
from employees
group by department_id
having avg(salary) = (
select max(avg_sal) from (select avg(salary) avg_sal
from employees
where department_id is not null
group by department_id) t_avg_sql
))
);
#15. Query the department number of the Department , It does not include job_id yes "ST_CLERK" Your department number
-- Mode one :
select department_id
from departments
where department_id not in (
select distinct department_id
from employees e1
where job_id = 'ST_CLERK'
);
-- Mode two :
select department_id
from departments d
where not exists (
select *
from employees e1
where d.department_id = e1.department_id and job_id = 'ST_CLERK'
);
#16. Select all employees without managers last_name
select last_name
from employees e1
where not exists(
select * from employees e2 where e1.manager_id = e2.employee_id
);
#17. Check the employee number 、 full name 、 Employment time 、 Wages , The manager of the employee is 'De Haan '
-- Mode one : Self join
select e1.employee_id,e1.last_name,e1.hiredate,e1.salary
from employees e1,employees e2
where e1.manager_id = e2.employee_id and e2.last_name = 'De Haan';
-- Mode two : Subquery
select employee_id,last_name,hiredate,salary
from employees
where manager_id in (
select employee_id from employees where last_name = 'De Haan'
);
#18. Query the employee number of employees in each department whose salary is higher than the average salary of the Department , Name and salary ( Correlation subquery )
-- Mode one :
select employee_id,salary,last_name
from employees e1
where salary > (
select avg(salary) from employees e2 where e1.department_id = e2.department_id
);
-- Mode two :
select employee_id,salary,last_name
from employees e,(select department_id,avg(salary) avg_sal from employees group by department_id) t_avg_sal
where e.department_id = t_avg_sal.department_id and e.salary > t_avg_sal.avg_sal;
#19. Query the number of departments under each department is greater than 5 Department name of ( Correlation subquery )I
select department_name
from departments d
where 5 < (
select count(*) from employees e where e.department_id = d.department_id
);
#20. The number of departments in each country is greater than 2 Country number of ( Correlation subquery )
select country_id
from locations l
where 2 < (
select count(*) from departments d where l.location_id = d.location_id
);
边栏推荐
- On the escape of inequality value
- Installation and use of logstash
- (树) 树状数组
- Summary of several common UML diagrams
- Record of user behavior log in SSO microservice Engineering
- 数据库范式和主码的选择
- String string is converted to jsonarray and parsed
- 成功解决之微服务@Value获取配置文件乱码问题
- Unit test of boot
- 项目实战四:用户登录及token访问验证(reids+jwt)
猜你喜欢

Wechat applet custom pop-up components

Installation and use of logstash

项目实战六:分布式事务-Seata

Solidity - 合约继承子合约包含构造函数时报错 及 一个合约调用另一合约view函数收取gas费用

Redis单点登陆系统+投票系统

威胁猎人必备的六个威胁追踪工具

Commodity seckill system

Crawl Douban to read top250 and import it into SqList database (or excel table)
![[kubernetes] kubernetes principle analysis and practical application (under update)](/img/37/40b8317a4d8b6f9c3acf032cd4350b.jpg)
[kubernetes] kubernetes principle analysis and practical application (under update)

抖音实战~分享模块~短视频下载(保存到相册)
随机推荐
Feign远程调用
Some cold knowledge about QT database development
To: Apple CEO Cook: great ideas come from constantly rejecting the status quo
Union, intersection and difference operations in SQL
Leetcode 238 product of arrays other than itself
The eigen library calculates the angle between two vectors
8VC Venture Cup 2017 - Final Round C. Nikita and stack
[kubernetes] kubernetes principle analysis and practical application (under update)
SSO微服务工程中用户行为日志的记录
关于不等式取值转义的思路
成功解决之Jenkins报错:The goal you specified requires a project to execute but there is no POM
Using recursion to find all gray codes with n bits
Tree array
redis 基础知识
Clion compiling catkin_ WS (short for ROS workspace package) loads cmakelists Txt problems
Why don't I recommend going to sap training institution for training?
Project practice 4: user login and token access verification (reids+jwt)
tsconfig. json
Solidity - contract inheritance sub contract contains constructor errors and one contract calls the view function of another contract to charge gas fees
Commodity seckill system