当前位置:网站首页>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 :

边栏推荐
- 基于可变参模板实现的线程池
- JVM_ 16_ Garbage collector
- 【C语言】详解线程回收函数 pthread_join
- [new function] ambire wallet integrates Metis network
- Webassembly learning - dynamic linking
- Gocd is good, but talk about Jenkins
- 要不是和阿里P7聊过,我也不知道自己是个棒槌
- Project development culture
- CANoe-如何在Trace窗口解析报文并显示信息(Program Node和结构体类型系统变量的使用)
- Libuv library overview and comparison of libevent, libev and libuv (Reprint)
猜你喜欢
![[C language] explain the thread exit function pthread_ exit](/img/fb/96db1c712370dbb216a06440ecdc5e.png)
[C language] explain the thread exit function pthread_ exit

moudo网络库剖析

快速开发项目-VScode插件

Redis cache penetration, cache breakdown, cache avalanche

Baidu AI Cloud service grid product CSM release 𞓜 hot public beta

iNFTnews | 元宇宙技术将带来全新的购物体验

如何创建 robots.txt 文件?

Live broadcast appointment AWS data everywhere series activities

SQL 数据记录如何上下行合并

yolox出现 RuntimeError: DataLoader worker (pid(s) 17724, 1364, 18928) exited unexpectedly
随机推荐
How sqlserver queries and removes results with null fields in the whole column
Analysis on the types of source code anti leakage technology
不使用union实现Mysql 列转行
Runtimeerror in yolox: dataloader worker (PID (s) 17724, 1364, 18928) exited unexpectedly
PostgreSQL has a cross database references are not implemented bug
Here comes Wi Fi 7. How strong is it?
String不同创建方式的区别
The virtual machine MySQL cannot be connected to the local computer
Redis cache penetration, cache breakdown, cache avalanche
webassembly学习-动态链接
iNFTnews | 元宇宙技术将带来全新的购物体验
Project development culture
Rapid development project -vscode plug-in
Developer scheme · environmental monitoring equipment (Xiaoxiong school IOT development board) connected to graffiti IOT development platform
PostgreSQL 出现cross-database references are not implemented的bug
快速开发项目-VScode插件
HCIE-Security Day41:理论学习:信息收集与网络探测
大神们 在富函数的open中从mysql连接池里取连接 连接池初始化是20个 如果富函数的并行度是1
【新功能】Ambire 钱包集成了 Metis 网络
SEAttention 通道注意力機制