当前位置:网站首页>100 important knowledge points that SQL must master: using subquery
100 important knowledge points that SQL must master: using subquery
2022-06-30 11:02:00 【Guge academic】
11.1 Subquery
SELECT The sentence is SQL Query for . All we've seen so far SELECT Statement both
It's a simple query , That is, a single statement to retrieve data from a single database table .
Inquire about (query)
whatever SQL Statements are queries . But the term generally refers to SELECT sentence .
SQL It also allows the creation of subqueries (subquery), That is, queries nested in other queries . Why?
Why should we do this ? The best way to understand this concept is to look at a few examples .
11.2 Use subqueries to filter
All the database tables used in this book are relational tables ( Description of each table and relationship ,
Please refer to the appendix A). Orders are stored in two tables . Each order contains the order number 、 Customer ID、
Order date , stay Orders Stored as a row in the table . The items of each order are stored in the relevant
OrderItems In the table . Orders The table does not store customer information , Store only customers ID. Customer's
The actual information is stored in Customers In the table .
Now? , If you need to list the ordered items RGAN01 All our customers , How to retrieve ? Next
List the specific steps .
(1) Search for items that contain RGAN01 All order numbers for .
(2) Retrieve the of all customers with the order numbers listed in the previous step ID.
(3) Retrieve all customers returned in the previous step ID Customer information for .
Each of the above steps can be performed as a separate query . You can put one SELECT language
The result returned by the clause is used for another SELECT Of the statement WHERE Clause .
You can also use subqueries to put 3 Combine multiple queries into one statement .
Article 1 with a SELECT The meaning of the sentence is very clear , It's right prod_id by RGAN01 All orders for
Single item , Retrieve its order_num Column . The output lists two orders containing this item :
Input ▼
SELECT order_num
FROM OrderItems
WHERE prod_id = 'RGAN01';
Output ▼
order_num
-----------
20007
20008
Now? , We know which order contains the item to be retrieved , Next, query and order 20007
and 20008 Relevant customers ID. Use the 5 The class introduces IN Clause , Write the following SELECT
sentence :
Input ▼
SELECT cust_id
FROM Orders
WHERE order_num IN (20007,20008);
Output ▼
cust_id
----------
1000000004
1000000005
Now? , Combine these two queries , Put the first query ( Return the order number ) Become a child
Inquire about . Please look at the following SELECT sentence :
Input ▼
SELECT cust_id
FROM Orders
WHERE order_num IN (SELECT order_num
FROM OrderItems
WHERE prod_id = 'RGAN01');
Output ▼
cust_id
----------
1000000004
1000000005
analysis ▼
stay SELECT In the sentence , Subqueries are always processed from the inside out . Dealing with the above SELECT language
Sentence tense ,DBMS In fact, two operations were performed .
First , It executes the following query :
SELECT order_num FROM orderitems WHERE prod_id='RGAN01'
This query returns two order numbers : 20007 and 20008 . then , These two values are expressed in IN The operator
The required comma separated format is passed to the external query WHERE Clause . External queries become :
SELECT cust_id FROM orders WHERE order_num IN (20007,20008)
You can see , The output is correct , Hard coded as before WHERE Clause returns the same value .
Tips : format SQL
Containing subqueries SELECT Statements are difficult to read and debug , They are even more complex
such . As shown above , Decompose the subquery into multiple rows and indent them appropriately , Can greatly
Simplify the use of subqueries .
By the way , This is where color coding works , well DBMS The client is out
For this reason, the color code is used SQL.
Now I got the order RGAN01 Of all our customers ID. The next step is to retrieve these customers
ID Customer information for . Retrieve two columns of SQL Statement for :
Input ▼
SELECT cust_name, cust_contact
FROM Customers
WHERE cust_id IN (1000000004,1000000005);
You can put WHERE Clause is converted to a subquery , Instead of hard coding these customers ID:
Input ▼
SELECT cust_name, cust_contact
FROM Customers
WHERE cust_id IN (SELECT cust_id
FROM Orders
WHERE order_num IN (SELECT order_num
FROM OrderItems
WHERE prod_id = 'RGAN01'));
Output ▼
cust_name cust_contact
----------------------------- --------------------
Fun4All Denise L. Stephens
The Toy Store Kim Howard
analysis ▼
In order to perform the above SELECT sentence ,DBMS In fact, three must be implemented SELECT sentence .
The innermost sub query returns a list of order numbers , This list is used for subqueries outside it WHERE
Clause . The external sub query returns the customer ID list , This customer ID Lists are used for outermost queries
Of WHERE Clause . The outermost query returns the required data .
so , stay WHERE Using subquery in clause can write powerful and flexible SQL
sentence . There is no limit to the number of subqueries that can be nested , However, in actual use, due to sex
The limits of energy , You cannot nest too many subqueries .
Be careful : It can only be a single column
As a subquery SELECT Statement can only query a single column . Attempting to retrieve multiple columns will return
error .
Be careful : Subqueries and performance
The code given here is valid , And obtained the desired results . however , Use subqueries and
Not always the most efficient way to perform this type of data retrieval . More discussion , Please refer to the first 12
course , This example will be given again .
11.3 Use subqueries as calculated fields
Another way to use subqueries is to create calculated fields . If you need to show Customers In the table
Total orders per customer . Order and corresponding customer ID Stored in Orders In the table .
Do this , Follow these steps :
(1) from Customers Retrieve the customer list from the table ;
(2) For each customer retrieved , Statistics of its in Orders The number of orders in the table .
As mentioned in the previous two lessons , have access to SELECT COUNT(*) Count the rows in the table , and
And by providing a WHERE Clause to filter a particular customer ID, For this customer only
Single count . for example , The following code is for customers 1000000001 Count the orders of :
Input ▼
SELECT COUNT(*) AS orders
FROM Orders
WHERE cust_id = 1000000001;
For every customer COUNT(*) , It should be treated as a subquery . Look at the code below :
Input ▼
SELECT cust_name,
cust_state,
(SELECT COUNT(*)
FROM Orders
WHERE Orders.cust_id = Customers.cust_id) AS orders
FROM Customers
ORDER BY cust_name;
Output ▼
cust_name cust_state orders
------------------------- ---------- ------
Fun4All IN 1
Fun4All AZ 1
Kids Place OH 0
The Toy Store IL 1
Village Toys MI 2
analysis ▼
This article SELECT The statement of Customers Each customer in the table returns three columns : cust_name 、
cust_state and orders . orders Is a calculated field , It is made up of... In parentheses
Subqueries are created . The sub query is executed once for each customer retrieved . In this case , The
The subquery is executed 5 Time , Because the search found 5 A customer .
In subquery WHERE Clause is the same as previously used WHERE The clause is slightly different , Because it uses
Fully qualified column names , Not just listing ( cust_id ). It specifies the table name and column name
( Orders.cust_id and Customers.cust_id ). Below WHERE The clause tells SQL,
Compare Orders In the table cust_id And currently from Customers Retrieved from table cust_id :
WHERE Orders.cust_id = Customers.cust_id
Separate the table name and column name with a period , This syntax must be used when it is possible to confuse column names .
In this case , There are two cust_id Column : In a Customers in , The other is
Orders in . If you do not use fully qualified column names ,DBMS Will think you should be right Orders In the table
Of cust_id Compare yourself . because
SELECT COUNT(*) FROM Orders WHERE cust_id = cust_id
Always returns Orders The total number of orders in the table , And this result is not what we want :
Input ▼
SELECT cust_name,
cust_state,
(SELECT COUNT(*)
FROM Orders
WHERE cust_id = cust_id) AS orders
FROM Customers
ORDER BY cust_name;
Output ▼
cust_name cust_state orders
------------------------- ---------- ------
Fun4All IN 5
Fun4All AZ 5
Kids Place OH 5
The Toy Store IL 5
Village Toys MI 5
Although subqueries are constructing this kind of SELECT Statements are extremely useful , However, it must be noted that the restrictions are ambiguous
The column of .
Be careful : Fully qualified column name
You've seen why fully qualified column names are used , If there is no specific specification, an error will be returned
False result , because DBMS Will misunderstand what you mean . occasionally , Due to conflicting column names
Resulting ambiguity , Can cause DBMS Throw error messages . for example , WHERE or ORDER
BY A column name specified by clause may appear in multiple tables . The good thing is , If in
SELECT Statement to operate on multiple tables , You should use fully qualified column names to avoid ambiguity .
Tips : More than one solution
As mentioned earlier in this lesson , Although the sample code given here works well , But it's not
It is the most effective way to solve this kind of data retrieval . Study in the next two lessons JOIN when , We
You will also encounter this example .
边栏推荐
- 【无标题】
- ESP32-C3入门教程 问题篇⑨——Core 0 panic‘ed (Load access fault). Exception was unhandled. vfprintf.c:1528
- Foresniffer tutorial: extracting data
- LVGL 8.2 re-coloring
- datax json说明
- [机缘参悟-34]:光锥之内皆命运
- CP2112使用USB转IIC通信教学示例
- 在IPhone12的推理延迟仅为1.6 ms!Snap等详析Transformer结构延迟,并用NAS搜出移动设备的高效网络结构...
- LeetCode Algorithm 86. Separate linked list
- Deep dive kotlin synergy (16): Channel
猜你喜欢

科普达人丨漫画图解什么是eRDMA?

Viewing technological changes through Huawei Corps (V): smart Park

CSDN blog operation team 2022 H1 summary

sCrypt 中的 ECDSA 签名验证

List介绍

The intelligent DNA molecular nano robot model is coming

LVGL 8.2 Image

深潜Kotlin协程(十六):Channel

煥發青春的戴爾和蘋果夾擊,兩大老牌PC企業極速衰敗

The first China Digital Collection conference will be held soon
随机推荐
Pytorch notes: validation, model eval V.S torch. no_ grad
【无标题】
MySQL export SQL script file
05_ Node JS file management module FS
LeetCode Algorithm 86. 分隔链表
LVGL 8.2 Image styling and offset
datax json说明
SQL必需掌握的100个重要知识点:联结表
ESP32-C3入门教程 IoT篇⑤——阿里云 物联网平台 EspAliYun RGB LED 实战之批量生产的解决方案
我们公司使用 7 年的这套通用解决方案,打通了几十个系统,稳的一批!
20万奖金池!【阿里安全 × ICDM 2022】大规模电商图上的风险商品检测赛火热报名中!...
第一届中国数字藏品大会即将召开
语音识别-基础(一):简介【语音转文本】
Unity Shader - 踩坑 - BRP 管线中的 depth texture 的精度问题(暂无解决方案,推荐换 URP)
时间复杂度与空间复杂度
蚂蚁金服笔试题:需求文档有什么可以量化的【杭州多测师】【杭州多测师_王sir】...
ESP32-C3入门教程 基础篇⑪——Non-Volatile Storage (NVS) 非易失性存储参数的读写
SQL必需掌握的100个重要知识点:更新和删除数据
MySQL导出sql脚本文件
在IPhone12的推理延迟仅为1.6 ms!Snap等详析Transformer结构延迟,并用NAS搜出移动设备的高效网络结构...