当前位置:网站首页>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 .
边栏推荐
- MySQL从入门到精通50讲(三十二)-ScyllaDB生产环境集群搭建
- Ant financial's written test question: what can be quantified in the requirements document? [Hangzhou multi tester] [Hangzhou multi tester \wang Sir]
- 深潜Kotlin协程(十七):演员
- 第一届中国数字藏品大会即将召开
- The number of users of the home-made self-developed system exceeded 400million, breaking the monopoly of American enterprises, and Google repented
- [leetcode 16] sum of three numbers
- 电化学氧气传感器寿命、工作原理及应用介绍
- SGD has many improved forms. Why do most papers still use SGD?
- MySQL export SQL script file
- Wireguard simple configuration
猜你喜欢

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

记一次ViewPager + RecyclerView的内存泄漏

matplotlib 笔记: contourf & contour

Go zero micro Service Practice Series (VIII. How to handle tens of thousands of order requests per second)

在IPhone12的推理延迟仅为1.6 ms!Snap等详析Transformer结构延迟,并用NAS搜出移动设备的高效网络结构...

The two e-commerce bigwigs' lacy news screens represent the return of e-commerce to normal, which will be beneficial to the real economy

8行代码实现快速排序,简单易懂图解!
![When does the database need to use the index [Hangzhou multi surveyors] [Hangzhou multi surveyors _ Wang Sir]](/img/2a/f07a7006e0259d78d046b30c761764.jpg)
When does the database need to use the index [Hangzhou multi surveyors] [Hangzhou multi surveyors _ Wang Sir]

Pytorch Notebook. Nn. Batchnorm1d

第一届中国数字藏品大会即将召开
随机推荐
Mysql database foundation: views and variables
ESP32-C3入门教程 问题篇⑨——Core 0 panic‘ed (Load access fault). Exception was unhandled. vfprintf.c:1528
Qt之实现QQ天气预报窗体翻转效果
OLAP数据库引擎如何选型?
[rust weekly database] num bigint - large integer
深潜Kotlin协程(十八):冷热数据流
电化学氧气传感器寿命、工作原理及应用介绍
LED driver library based on Hal Library
The number of users of the home-made self-developed system exceeded 400million, breaking the monopoly of American enterprises, and Google repented
基于HAL库的LED驱动库
Dell et Apple, deux entreprises de PC établies, se sont effondrées rapidement
China will force a unified charging interface. If Apple does not bow its head, iPhone will be kicked out of the Chinese market
LVGL 8.2 Simple Colorwheel
Algorithme leetcode 86. Liste des liens séparés
单片机 MCU 固件打包脚本软件
LVGL 8.2 Simple Image button
煥發青春的戴爾和蘋果夾擊,兩大老牌PC企業極速衰敗
MySQL导出sql脚本文件
数据库什么时候需要使用索引【杭州多测师】【杭州多测师_王sir】
[rust daily] several new libraries were released on January 23, 2021