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

边栏推荐
- 女程序员晒出5月的工资条:工资是高,但是真累,网友评论炸锅了
- JSX的基本使用
- 【HackTheBox】dancing(SMB)
- Technology cloud report: side B of mixed office: how to have both security and efficiency?
- sql数据库存储过程写法
- 1019 数字黑洞
- CDC2.2.1还不支持postgresql14.1么?基于pgbouncer连接方式下,以5433
- SQL database stored procedure writing method
- Is the increased life insurance off the shelf? What additional life insurance products are available now?
- 1016 部分A+B
猜你喜欢

Apifox : 不仅是Api调试工具,更是开发团队的协作神器

Blue Bridge Cup ruler method

赚钱的5个层次,你在哪一层?

SEAttention 通道注意力机制

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

Error accessing database

If you choose the right school, you can enter Huawei as a junior college. I wish I had known

【C语言】解决 “address of stack memory associated with local variable ‘num‘ returned”

Basic use of JSX

Rapid development project -vscode plug-in
随机推荐
CDC2.2.1还不支持postgresql14.1么?基于pgbouncer连接方式下,以5433
Canoe- how to parse messages and display information in the trace window (use of program node and structure type system variables)
Libuv library overview and comparison of libevent, libev and libuv (Reprint)
Live broadcast appointment AWS data everywhere series activities
Ansible best practices playbook different context rights raising demo
Establishment of small and medium-sized enterprise network
Lua protobuff Emmy Lua wheel
[C language] explain the thread exit function pthread_ exit
CANoe-如何在Trace窗口解析报文并显示信息(Program Node和结构体类型系统变量的使用)
Rapid development project -vscode plug-in
Talking about Canary deployment
1017 a divided by B
PostgreSQL has a cross database references are not implemented bug
Runtimeerror in yolox: dataloader worker (PID (s) 17724, 1364, 18928) exited unexpectedly
Practical part: solving the function conflict between swagger and user-defined parameter parser
项目开发修养
Ask a simple question about SQL
Analysis of moudo Network Library
干货丨微服务架构是什么?有哪些优点和不足?
自己动手搭建一个简单的网站