当前位置:网站首页>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 .
边栏推荐
- 2022 special operation certificate examination question bank and simulation examination for safety management personnel of fireworks and firecrackers business units
- Study on chemical properties and technology of biovendor rage ELISA Kit
- MCLK configuration of Qualcomm platform camera
- 数据中台:数据治理的建设思路以及落地经验
- MySQL export database dictionary to excel file
- What does mysql---where 1=1 mean
- Disable right-click, keyboard open console events
- [JVM] - Division de la mémoire en JVM
- [skywalking] learn distributed link tracking skywalking at one go
- WordPress zibll sub theme 6.4.1 happy version is free of authorization
猜你喜欢
mysql导出数据库字典成excel文件
Function reentry caused by Keil C51's data overlaying mechanism
Binder面试之:内存管理单元
How high is the gold content of grade II cost engineer certificate? Just look at this
Oracle 常用基础函数
Based on the order flow tool, what can we see?
分享|智慧环保-生态文明信息化解决方案(附PDF)
Interpretation of cloud native microservice technology trend
【无标题】drv8825步进电机驱动板子原理图
Carboxylic acid study: lumiprobe sulfoacyanine 7 dicarboxylic acid
随机推荐
Line animation
Comparison between relational database and document database
JS text box loses focus to modify width text and symbols
Jdbc的使用
Steve Jobs' speech at Stanford University -- follow your heart
Have you finished the examination of level II cost engineer? There are also qualification regulations!
Lumiprobe cell imaging analysis: PKH26 cell membrane labeling kit
Latest Windows version 5.0.14 of redis
How to develop the language pack in the one-to-one video chat source code
OpenSSL client programming: SSL session failure caused by an obscure function
博客登录框
Study on modified triphosphate: lumiprobe amino-11-ddutp
JSP
Programmer - Shepherd
Reactive dye research: lumiprobe af594 NHS ester, 5-isomer
刘海屏手机在部分页面通过[[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom得到底部安全区高度为0问题
数据中台:六问数据中台
[JVM] - memory partition in JVM
Why don't big manufacturers use undefined
Keil C51的Data Overlaying机制导致的函数重入问题