当前位置:网站首页>100 important knowledge points that SQL must master: Combined Query
100 important knowledge points that SQL must master: Combined Query
2022-06-30 11:06:00 【Guge academic】
14.1 Combination query
Most of the SQL A query contains only a single bar of data returned from one or more tables SELECT sentence .
however ,SQL It also allows multiple queries to be executed ( multiple SELECT sentence ), And take the result as a
Query result sets return . These composite queries are often referred to as and (union) Or composite query
(compound query).
There are two main situations where you need to use composite queries :
Return structural data from different tables in a query ;
Perform multiple queries on a table , Press a query to return data .
Tips : Combine queries and multiple WHERE Conditions
Most of the time , Combining two queries with the same table does the same job as having multiple WHERE
A query with Clause conditions does the same thing . let me put it another way , Any with multiple
WHERE Clause SELECT Statements can be used as a combined query , Below you can see
To this point .
14.2 Create a composite query
You can use UNION Operator to combine several SQL Inquire about . utilize UNION , More than one... Can be given
SELECT sentence , Combine their results into a result set .
14.2.1 Use UNION
Use UNION It's simple , All you have to do is give each SELECT sentence , In each statement
Put keywords between UNION .
for instance , If necessary Illinois、Indiana and Michigan Wait for all the customers in several states in the United States
Customer's statement , Also want to include all... Regardless of the state Fun4All . Of course you can use
WHERE Clause to do this , But this time we use UNION .
As mentioned above , establish UNION Involves writing multiple SELECT sentence . First, let's look at a single statement :
Input ▼
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_state IN ('IL','IN','MI');
Output ▼
cust_name cust_contact cust_email
----------- ------------- ------------
Village Toys John Smith [email protected]
Fun4All Jim Jones [email protected]
The Toy Store Kim Howard NULL
Input ▼
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_name = 'Fun4All';
Output ▼
cust_name cust_contact cust_email
----------- ------------- ------------
Fun4All Jim Jones [email protected]
Fun4All Denise L. Stephens [email protected]
analysis ▼
Article 1 with a SELECT hold Illinois、Indiana、Michigan The abbreviations of other states are passed to IN Clause ,
Retrieve all the rows in these States . Second SELECT Use a simple equality test to find all
Fun4All . You will find a record in two results , Because it satisfies twice
Conditions .
Combine these two statements , It can be done as follows :
Input ▼
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_state IN ('IL','IN','MI')
UNION
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_name = 'Fun4All';
Output ▼
cust_name cust_contact cust_email
----------- ----------- ----------------
Fun4All Denise L. Stephens [email protected]
Fun4All Jim Jones [email protected]
Village Toys John Smith [email protected]
The Toy Store Kim Howard NULL
analysis ▼
This statement consists of the first two SELECT Sentence composition , In between UNION Keyword separation .
UNION instructions DBMS Implement these two articles SELECT sentence , And combine the output into a query
Result set .
For ease of reference , Here are some examples of using WHERE Clause instead of UNION The same query :
Input ▼
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_state IN ('IL','IN','MI')
UNION
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_name = 'Fun4All';
In this simple example , Use UNION Maybe it's better than using WHERE The clause is more complex . but
For more complex filtering conditions , Or from multiple tables ( Not a watch ) To retrieve data from
situation , Use UNION Make it easier to deal with .
Tips : UNION The limitation of
Use UNION Combine SELECT Number of statements ,SQL There are no standard restrictions . however , most
OK, let's refer to the specific DBMS file , Find out if it's right UNION The largest that can be combined
The number of statements is limited .
Be careful : Performance issues
Most good DBMS Use internal query optimizer , Dealing with various items SELECT Statement before
Combine them . Theoretically speaking , This means using multiple... From a performance point of view WHERE Clause condition
still UNION There should be no practical difference . But I'm talking about theory , In practice, most
The query optimizer is not in the ideal state , So it's best to test these two methods ,
See which job is better .
14.2.2 UNION The rules
You can see , UNION Very easy to use , But there are several rules to note when combining .
UNION There must be two or more SELECT Sentence composition , Use keywords between statements
UNION Separate ( therefore , If you combine four SELECT sentence , Three... Will be used UNION
keyword ).
UNION Each query in must contain the same columns 、 Expression or aggregate function ( however ,
The columns do not need to be listed in the same order ).
Column data types must be compatible with : The type doesn't have to be exactly the same , But it has to be DBMS Can imply
Type of conversion ( for example , Different numeric types or different date types ).
explain :UNION Column name of
If combined UNION The use of SELECT Statement encountered different column names , What will be returned
What's the name ? for instance , If a statement is SELECT prod_name , And the other one
The sentence is SELECT productname , So what is the name returned by the query result ?
The answer is that it returns the first name , This example will return prod_name , and
No matter the second different name . This also means that you can use an alias for the first name ,
So return a name you want .
This behavior has an interesting side effect . Because only the first name is used , So think
You can only use this name to sort . Take our example , It can be used ORDER BY
prod_name Sort the results , If written ORDER BY productname Will go wrong ,
Because the query result is not called productname The column of .
If these basic rules or restrictions are observed , Then you can put UNION For any data retrieval
operation .
14.2.3 Include or cancel duplicate lines
go back to 14.2.1 section , Let's look at the SELECT sentence . Notice that the statements are executed separately
when , Article 1 with a SELECT Statement returns 3 That's ok , Second SELECT Statement returns 2 That's ok . And in the
use UNION Combine two SELECT After the statement , Only return 4 Yes, but not. 5 That's ok .
UNION Duplicate rows are automatically removed from the query result set ; let me put it another way , Its behavior is related to one
strip SELECT Use more than one in a statement WHERE The clauses and conditions are the same . because Indiana The state has a
Fun4All Company , So two SELECT Statements return the row . Use UNION when , repeat
The row of is automatically cancelled .
This is a UNION Default behavior of , You can change it if you like . in fact , If you want to go back
All matching lines , You can use UNION ALL instead of UNION .
Please see the following example :
Input ▼
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_state IN ('IL','IN','MI')
UNION ALL
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_name = 'Fun4All';
Output ▼
cust_name cust_contact cust_email
----------- ------------- ------------
Village Toys John Smith [email protected]
Fun4All Jim Jones [email protected]
The Toy Store Kim Howard NULL
Fun4All Jim Jones [email protected]
Fun4All Denise L. Stephens [email protected]
analysis ▼
Use UNION ALL ,DBMS Do not cancel duplicate lines . therefore , Return here 5 That's ok , among
A line appears twice .
Tips : UNION And WHERE
At the beginning of this lesson, we said , UNION Almost always complete with multiple WHERE On the same terms
The job of . UNION ALL by UNION A form of , It's done WHERE Clause complete
Can't work . If you really need all the matching lines of each condition to appear ( Include repeating lines ),
Must use UNION ALL , instead of WHERE .
14.2.4 Sort the combined query results
SELECT The output of the statement is ORDER BY Clause ordering . In use UNION When combining queries , only
Can use one ORDER BY Clause , It must be on the last SELECT After statement . Yes
Apply to result set , There is no way to sort parts of , And sort another... In another way
Part of the situation , Therefore, it is not allowed to use more than one ORDER BY Clause .
The following example is for the previous UNION Sort the returned results :
Input ▼
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_state IN ('IL','IN','MI')
UNION
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_name = 'Fun4All'
ORDER BY cust_name, cust_contact;
Output ▼
cust_name cust_contact cust_email
----------- ------------- -------------
Fun4All Denise L. Stephens [email protected]
Fun4All Jim Jones [email protected]
The Toy Store Kim Howard NULL
Village Toys John Smith [email protected]
analysis ▼
This article UNION In the last one SELECT After the statement ORDER BY Clause . although ORDER
BY The clause seems to be just the last one SELECT Components of the statement , But actually DBMS take
Use it to sort all SELECT All results returned by the statement .
explain : Other types UNION
some DBMS It also supports two other UNION : EXCEPT ( Sometimes called MINUS ) You can use
To retrieve rows that exist only in the first table but do not exist in the second table ; and INTERSECT
Can be used to retrieve rows that exist in both tables . actually , these UNION Rarely used , because
For the same result, we can get .
Tips : Manipulate multiple tables
For simplicity , The examples in this lesson are all used UNION To combine multiple queries for the same table
Inquiry . actually , UNION It is also useful when you need to combine data from multiple tables , Even if there is
Tables that do not match column names , under these circumstances , Can be UNION Combined with alias , retrieval
A result set .
边栏推荐
- SQL必需掌握的100个重要知识点:创建和操纵表
- 智能DNA分子纳米机器人模型来了
- [untitled]
- 深潜Kotlin协程(十六):Channel
- SQL必需掌握的100个重要知识点:使用视图
- 100 important knowledge points that SQL must master: join table
- LVGL 8.2 Checkboxes as radio buttons
- SQL必需掌握的100个重要知识点:使用存储过程
- Classic interview question: responsible modules, how do you design test cases for these function points? [Hangzhou multi surveyors] [Hangzhou multi surveyors \wang Sir]
- 再测云原生数据库性能:PolarDB依旧最强,TDSQL-C、GaussDB变化不大
猜你喜欢

China will force a unified charging interface. If Apple does not bow its head, iPhone will be kicked out of the Chinese market

File sharing server

小程序中读取腾讯文档的表格数据

CP2112使用USB转IIC通信教学示例

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

从开源项目探讨“FPGA挖矿”的本质

pytorch 筆記 torch.nn.BatchNorm1d

The number of users of the home-made self-developed system exceeded 400million, breaking the monopoly of American enterprises, and Google repented

数据库什么时候需要使用索引【杭州多测师】【杭州多测师_王sir】

MySQL export SQL script file
随机推荐
[understanding of opportunity -34]: fate is within the light cone
林克庆到番禺区调研“发展要安全”工作 以“时时放心不下”责任感抓好安全发展各项工作
Pytorch notes torch nn. BatchNorm1d
sCrypt 中的 ECDSA 签名验证
LVGL 8.2 Image
创建型-配置工厂
Jetpack Compose DropdownMenu跟随手指点击位置显示
LVGL 8.2 Checkboxes as radio buttons
CSDN blog operation team 2022 H1 summary
【leetcode 16】三数之和
[机缘参悟-34]:光锥之内皆命运
[STL source code analysis] iterator
Sarsa笔记
训练一个图像分类器demo in PyTorch【学习笔记】
经典面试题:负责的模块,针对这些功能点你是怎么设计测试用例的?【杭州多测师】【杭州多测师_王sir】...
LeetCode Algorithm 86. Separate linked list
When does the database need to use the index [Hangzhou multi surveyors] [Hangzhou multi surveyors _ Wang Sir]
matplotlib 笔记: contourf & contour
LVGL8.2 Simple Checkboxes
AMS源码解析