当前位置:网站首页>MySQL subquery
MySQL subquery
2022-06-29 04:19:00 【wgchen~】
Read the directory
Sample database
download :https://download.csdn.net/download/weiguang102/80930478
MySQL Subquery write complex query statements and explain related subquery concepts
MySQL A subquery is nested within another query ( Such as SELECT,INSERT,UPDATE or DELETE) Query in . in addition ,MySQL A subquery can be nested in another subquery .
MySQL Subqueries are called internal queries , Queries that contain subqueries are called external queries . Subqueries can be used anywhere expressions are used , And must be closed in parentheses .
The following query is returned in the United States (USA) Employees working in the office .
SELECT lastName, firstName
FROM employees
WHERE officeCode IN (
SELECT officeCode
FROM offices
WHERE country = 'USA'
);

In this case :
The subquery returns all office codes for offices located in the United States .
The external query selects the last name and first name of the employee working in the office whose office code is in the result set returned by the sub query .


MySQL Subquery in WHERE clause
We will use the example payments Table .
payments The table structure of the table is as follows 
MySQL Subquery and comparison operator
You can use the comparison operator , for example =,>,< Compare the single value returned by the subquery with WHERE Clause .
for example , The following query returns the customer with the maximum payment amount .
SELECT customerNumber, checkNumber, amount
FROM payments
WHERE amount = (
SELECT MAX(amount)
FROM payments
);

Except for equality operators , You can also use greater than (>), Less than (<) And so on .
for example , You can use a subquery to find customers whose payments are greater than the average . First , Use subqueries to calculate usage AVG Average payment for aggregate function . then , In an external query , Query the payment that is greater than the average payment returned by the sub query . Refer to the following query statement
SELECT customerNumber, checkNumber, amount
FROM payments
WHERE amount > (
SELECT AVG(amount)
FROM payments
);

have IN and NOT IN The operator of the MySQL Subquery
If a subquery returns multiple values , Can be in WHERE Used in clauses IN or NOT IN Operator and other operators .
View the... Of the following customer and order forms ER chart

for example , You can use the NOT IN Operator to find customers who have not placed any orders , As shown below :
SELECT customerName
FROM customers
WHERE customerNumber NOT IN (
SELECT DISTINCT customerNumber
FROM orders
);

FROM In Clause MySQL Subquery
stay FROM When using subqueries in clause , The result set returned from the subquery will be used as a temporary table . This table is called a derived table or materialized subquery .
The following sub query will find the largest... In the order table , Minimum and mean :
SELECT
MAX(items),
MIN(items),
FLOOR(AVG(items))
FROM (
SELECT orderNumber, COUNT(orderNumber) AS items
FROM orderdetails
GROUP BY orderNumber
) lineitems;


MySQL Subqueries use subqueries of data in external queries
In the previous example , Notice that a subquery is independent . This means that you can execute subqueries as standalone queries , for example :
SELECT
orderNumber,
COUNT(orderNumber) AS items
FROM
orderdetails
GROUP BY orderNumber;

Unlike independent subqueries , Related subqueries are subqueries that use data from external queries .
let me put it another way , The associated subquery depends on the external query .
Evaluate the relevant sub query for each row in the external query .
In the following query , We query and select products whose purchase price is higher than the average purchase price of products in each product line .

SELECT productname, buyprice
FROM products p1
WHERE buyprice > (
SELECT AVG(buyprice)
FROM products
WHERE productline = p1.productline
);

For each line of product line that changes , Each product line performs internal queries .
therefore , The average purchase price will also change . The external query only filters the products whose purchase price is greater than the average purchase price of each product line in the sub query .
MySQL Subquery and EXISTS and NOT EXISTS
When subquery and EXISTS or NOT EXISTS When operators are used together , The subquery returns a Boolean value of TRUE or FALSE Value .
The following query describes the relationship with EXISTS Subqueries used with the :
SELECT
*
FROM
table_name
WHERE EXISTS(subquery);
In the query above , If the subquery (subquery) There are any rows returned , be EXISTS Subquery returns TRUE, Otherwise return to FALSE.
Usually used in related subqueries EXISTS and NOT EXISTS.
Let's take a look at an example orders and orderDetails surface :

The total amount of the following query selections is greater than 60000 Sales orders for .
SELECT orderNumber, SUM(priceEach * quantityOrdered) AS total
FROM orderdetails
INNER JOIN orders USING (orderNumber)
GROUP BY orderNumber
HAVING SUM(priceEach * quantityOrdered) > 60000;



As shown above , return 3 Row data , This means that there are 3 The total amount of sales orders is greater than 60000.
You can use the above query as a related subquery , By using EXISTS Operator to find at least one total greater than 60000 Customer information of the sales order :
SELECT customerNumber, customerName
FROM customers
WHERE EXISTS (
SELECT orderNumber, SUM(priceEach * quantityOrdered)
FROM orderdetails
INNER JOIN orders USING (orderNumber)
WHERE customerNumber = customers.customerNumber
GROUP BY orderNumber
HAVING SUM(priceEach * quantityOrdered) > 60000
);
Execute the above query , The following results are obtained :

边栏推荐
- [hackthebox] dancing (SMB)
- 剑指 Offer II 040. 矩阵中最大的矩形
- Logstash starts too slowly or even gets stuck
- Practical part: solving the function conflict between swagger and user-defined parameter parser
- 1015 theory of virtue and talent
- SqlServer如何查询除去整列字段为null的结果
- String differences between different creation methods
- 快速开发项目-VScode插件
- Establishment of small and medium-sized enterprise network
- 项目开发修养
猜你喜欢

Why are you a test / development programmer? Can you recall

Blue Bridge Cup ruler method

【HackTheBox】dancing(SMB)

Anaconda自带的Spyder编辑器启动报错问题

Daily practice - February 15, 2022

Technology: how to design zkvm circuit

The second meeting of the Second Council of Euler open source community was held, and Xinhua III, hyperfusion and Godson Zhongke became members of the Council

Seattention channel attention mechanism

C language -- branch structure

Multi machine LAN office artifact rustdesk use push!!!
随机推荐
快速开发项目-VScode插件
自己动手搭建一个简单的网站
Remote connection of raspberry pie in VNC Viewer Mode
[new function] ambire wallet integrates Metis network
How sqlserver queries and removes results with null fields in the whole column
Nuxt - set SEO related tags, page titles, icons, etc. separately for each page (page configuration head)
Ansible best practices playbook different context rights raising demo
Nuxt - 每个页面单独设置 SEO 相关标签及网页标题、图标等(页面配置 head)
Five thousand years of China
源代码防泄露技术种类浅析
[C language] explain the thread exit function pthread_ exit
1016 部分A+B
SQL two columns become multi row filter display
SEAttention 通道注意力机制
lua-protobuff emmy-lua 轮子
赚钱的5个层次,你在哪一层?
[Brillouin phenomenon] Study on simultaneous measurement system of Brillouin temperature and strain distribution in optical fiber
Implementation of b+ tree index based on xlsx
How to create robots Txt file?
【C语言】开启一个线程