当前位置:网站首页>Mysql-16-subquery
Mysql-16-subquery
2022-06-28 05:32:00 【Rusty well began】
Subquery refers to a query that is nested within another query statement by one query statement , This feature comes from MySQL 4.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 .
1. Demand analysis and problem solving
1.1 Practical problems 
Existing solutions :
# Mode one :
SELECT salary
FROM employees
WHERE last_name = 'Abel';
SELECT last_name,salary
FROM employees
WHERE salary > 11000;
# Mode two : Self join
SELECT e2.last_name,e2.salary
FROM employees e1,employees e2
WHERE e1.last_name = 'Abel'
AND e1.`salary` < e2.`salary`
# Mode three : Subquery
SELECT last_name,salary
FROM employees
WHERE salary > (
SELECT salary
FROM employees
WHERE last_name = 'Abel'
);

1.2 The basic use of subqueries
- The basic syntax structure of subquery :

- Subquery ( Internal query ) Execute once 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
1.3 Classification of subqueries
Classification 1:
We return one or more records according to the results of internal query , Sub queries are divided into Single line sub query 、 Multi line sub query .
Single line sub query

Multi line sub query

Classification 2:
We check whether the query is executed more than once , Divide the subquery into relevant ( Or associated ) Subquery and Unrelated ( Or unrelated ) Subquery .
The subquery queries the data results from the data table , If this data result is executed only once , The data result is then executed as a condition of the main query , Then such a subquery is called an unrelated subquery .
Again , If the subquery needs to be executed multiple times , That is, in the form of circulation , Start with an external query , Each time, the sub query is passed in for query
Inquiry , The results are then fed back to the outside world , This nested execution is called related subquery .
2. Single line sub query
2.1 Single line comparison operator
| The operator | meaning |
|---|---|
| = | equal to |
| > | greater than |
| >= | greater than or equal to |
| < | less than |
| <= | less than or equal to |
| <> | not equal to |
2.2 Code example
subject : Query salary greater than 149 Information of the employee whose salary is No 

subject : 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);

subject : 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);

subject : Query and 141 Number or 174 Of employee No manager_id and department_id Of the same other employees employee_id,manager_id,department_id
Realization way 1: Unpaired comparison
SELECT employee_id, manager_id, department_id
FROM employees
WHERE manager_id IN
(SELECT manager_id
FROM employees
WHERE employee_id IN (174,141))
AND department_id IN
(SELECT department_id
FROM employees
WHERE employee_id IN (174,141))
AND employee_id NOT IN(174,141);
Realization way 2: Compare in pairs
SELECT employee_id, manager_id, department_id
FROM employees
WHERE (manager_id, department_id) IN
(SELECT manager_id, department_id
FROM employees
WHERE employee_id IN (141,174))
AND employee_id NOT IN (141,174);
2.3 HAVING Subqueries in
- First, execute the subquery .
- To the... In the main query HAVING Clause returns the result .
subject : The minimum wage is greater than 50 The Department of minimum wage id And its minimum wage
SELECT department_id, MIN(salary)
FROM employees
GROUP BY department_id
HAVING MIN(salary) >
(SELECT MIN(salary)
FROM employees
WHERE department_id = 50);
2.4 CASE Subqueries in
stay CASE Single column subqueries are used in expressions :
subject : Explicit employee employee_id,last_name and location. among , If employee department_id And location_id by 1800 Of department_id identical , be location by ’Canada’, The rest are ’USA’.
SELECT employee_id, last_name,
(CASE department_id
WHEN
(SELECT department_id FROM departments
WHERE location_id = 1800)
THEN 'Canada' ELSE 'USA' END) location
FROM employees;
2.5 Null value problem in subquery
SELECT last_name, job_id
FROM employees
WHERE job_id =
(SELECT job_id
FROM employees
WHERE last_name = 'Haas');

The subquery does not return any rows
2.5 Illegal use of subquery
SELECT employee_id, last_name
FROM employees
WHERE salary =
(SELECT MIN(salary)
FROM employees
GROUP BY department_id);

Multi line subqueries use single line comparators
3. Multi line sub query
- Also known as set comparison subquery
- Inner query returns multiple rows
- Use the multiline comparison operator
3.1 Multiline comparison operator
| The operator | meaning |
|---|---|
| IN | Equal to any one of the list |
| ANY | It needs to be used with the single line comparison operator , Compare with a value returned by a subquery |
| ALL | It needs to be used with the single line comparison operator , Compare with all the values returned by the subquery |
| SOME | It's actually ANY Another name for , The same effect , Commonly used ANY |
experience ANY and ALL The difference between
3.2 Code example
subject : Return to other job_id Middle ratio job_id by ‘IT_PROG’ Employee number of any low paid employee in the Department 、 full name 、job_id as well as salary

subject : Return to other job_id Middle ratio job_id by ‘IT_PROG’ Employee number of all employees in the Department with low salary 、 full name 、job_id as well as salary

subject : Query the Department with the lowest average wage id
# The way 1:
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
) dept_avg_sal
)
# The way 2:
SELECT department_id
FROM employees
GROUP BY department_id
HAVING AVG(salary) <= ALL (
SELECT AVG(salary) avg_sal
FROM employees
GROUP BY department_id
)
3.3 The null problem
SELECT last_name
FROM employees
WHERE employee_id NOT IN (
SELECT manager_id
FROM employees
);

4. Correlation subquery
4.1 Related sub query execution process
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 Associated subquery .
Related sub queries are executed row by row , Each row of the main query executes a subquery .

explain : The columns in the main query are used in the subquery
4.2 Code example
subject : 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 : Correlation subquery 
Mode two : stay FROM Use subqueries in
SELECT last_name,salary,e1.department_id
FROM employees e1,(SELECT department_id,AVG(salary) dept_avg_sal FROM employees GROUP
BY department_id) e2
WHERE e1.`department_id` = e2.department_id
AND e2.dept_avg_sal < e1.`salary`;
from Subquery of type : Subquery is used as from Part of , The subquery should use () Lead up , And alias this subquery , Think of it as a “ Temporary virtual table ” To use .
stay ORDER BY Use subqueries in :
subject : 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`
);
subject : if employees In the table employee_id And job_history In the table employee_id The same number is not less than 2, Output these same id Of our employees employee_id,last_name And its job_id
SELECT e.employee_id, last_name,e.job_id
FROM employees e
WHERE 2 <= (SELECT COUNT(*)
FROM job_history
WHERE employee_id = e.employee_id);
4.3 EXISTS And NOT EXISTS keyword
Associated subqueries are usually associated with EXISTS Operators are used together , Used to check whether there are qualified rows in the sub query .
If there are no qualified rows in the subquery :- Conditional return FALSE
- Continue to find... In subqueries
If there are qualified rows in the subquery :- Do not continue to find in subquery
- Conditional return TRUE
NOT EXISTS Keyword means that if there is no condition , Then return to TRUE, Otherwise return to FALSE.
subject : Query company managers employee_id,last_name,job_id,department_id Information
Mode one :
SELECT employee_id, last_name, job_id, department_id
FROM employees e1
WHERE EXISTS ( SELECT *
FROM employees e2
WHERE e2.manager_id =
e1.employee_id);
Mode two : Self join
SELECT DISTINCT e1.employee_id, e1.last_name, e1.job_id, e1.department_id
FROM employees e1 JOIN employees e2
WHERE e1.employee_id = e2.manager_id;
Mode three :
SELECT employee_id,last_name,job_id,department_id
FROM employees
WHERE employee_id IN (
SELECT DISTINCT manager_id
FROM employees
);
subject : Inquire about departments In the table , There is no in employees Of the departments in the table department_id and department_name
SELECT department_id, department_name
FROM departments d
WHERE NOT EXISTS (SELECT 'X'
FROM employees
WHERE department_id = d.department_id);

4.4 Related updates
UPDATE table1 alias1
SET column = (SELECT expression
FROM table2 alias2
WHERE alias1.column = alias2.column);
Use related subqueries to update data from one table to another .
subject : stay employees Add one department_name Field , The data is the Department name corresponding to the employee
# 1)
ALTER TABLE employees
ADD(department_name VARCHAR2(14));
# 2)
UPDATE employees e
SET department_name = (SELECT department_name
FROM departments d
WHERE e.department_id = d.department_id);
4.4 Relevant delete
DELETE FROM table1 alias1
WHERE column operator (SELECT expression
FROM table2 alias2
WHERE alias1.column = alias2.column);
Use related subqueries to delete data from one table based on data from another .
subject : Delete table employees in , And emp_history Data from all tables
DELETE FROM employees e
WHERE employee_id in
(SELECT employee_id
FROM emp_history
WHERE employee_id = e.employee_id);
5. Throw a question
problem : Whose pay ratio is Abel The height of ?
answer :
# The way 1: Self join
SELECT e2.last_name,e2.salary
FROM employees e1,employees e2
WHERE e1.last_name = 'Abel'
AND e1.`salary` < e2.`salary`
# The way 2: Subquery
SELECT last_name,salary
FROM employees
WHERE salary > (
SELECT salary
FROM employees
WHERE last_name = 'Abel'
);
problem : Are the above two methods good or bad ?
answer : Good self connection mode !
Subqueries can be used in the title , You can also use self connection . In general, it is recommended that you use self connection , Because in many DBMS In the process of processing , The processing speed of self join is much faster than sub query .
It can be understood in this way : Sub query is actually the condition judgment after query through unknown table , The self connection is to judge the conditions through the known self data table , So in most cases DBMS Self join processing has been optimized in .
边栏推荐
- Zzuli:1072 frog climbing well
- Leecode question brushing-ii
- [Verilog quick start of Niuke online question brushing series] ~ one out of four multiplexer
- MySQL export query results to excel file
- [Linux] - using xshell to install MySQL on Linux and realize the deployment of webapp
- 【LeetCode】12、整数转罗马数字
- Gee learning notes 3- export table data
- How does the power outlet transmit electricity? Simple problems that have plagued my little friend for so many years
- Can wechat applets import the data in the cloud development database into makers with one click in the map component
- Oracle 条件、循环语句
猜你喜欢

【Linux】——使用xshell在Linux上安装MySQL及实现Webapp的部署

Carboxylic acid study: lumiprobe sulfoacyanine 7 dicarboxylic acid

Bidirectional level conversion circuit

Function reentry caused by Keil C51's data overlaying mechanism

JSP connects with Oracle to realize login and registration (simple)

Binder面试之:内存管理单元

Sharing | intelligent environmental protection - ecological civilization informatization solution (PDF attached)

The heading angle of sliceplane is the same as that of math Corresponding transformation relation of atan2 (y, x)

Why is point shield cloud forced to quit playing?
![[Linux] - using xshell to install MySQL on Linux and realize the deployment of webapp](/img/07/e044a6ef14a6576dbee1c6a009ab4f.png)
[Linux] - using xshell to install MySQL on Linux and realize the deployment of webapp
随机推荐
数据仓库:DWS层设计原则
[untitled] drv8825 stepping motor drive board schematic diagram
Application of Beidou No.3 short message terminal in dam safety monitoring scheme
[JVM series] JVM tuning
jq图片放大器
Shutter nestedscrollview sliding folding head pull-down refresh effect
Can wechat applets import the data in the cloud development database into makers with one click in the map component
双向电平转换电路
JS中的链表(含leetcode例题)<持续更新~>
Solution of dam safety automatic monitoring system for medium and small reservoirs
Detailed usage configuration of the shutter textbutton, overview of the shutter buttonstyle style and Practice
Jdbc的使用
如何在您的Shopify商店中添加实时聊天功能?
Based on the order flow tool, what can we see?
SlicePlane的Heading角度与Math.atan2(y,x)的对应转换关系
WordPress zibll sub theme 6.4.1 happy version is free of authorization
Enum
【无标题】drv8825步进电机驱动板子原理图
MySQL 45 talk | 05 explain the index in simple terms (Part 2)
Docker安装Mysql5.7并开启binlog