当前位置:网站首页>Yyds dry goods counting SQL sub query
Yyds dry goods counting SQL sub query
2022-06-27 20:24:00 【51CTO】
Subquery is also called complex query , Why is a subquery called a complex query ? Because subqueries are equivalent to nested queries , Because of nesting, the complexity can be magnified almost infinitely ( Unlimited Nesting ), Therefore, it is called complex query . The following is an example of the simplest subquery :
The above example is equivalent to SELECT pv FROM test, But because the location of the table is replaced by a new query , So it becomes a complex query ! So complex queries don't have to be really complex , It is even possible to write complex queries that are equivalent to ordinary queries , To avoid this meaningless behavior .
We also want to take this opportunity to understand why subqueries can do this .
Understand the nature of queries
When we look up a table , What does the database think we're looking for ?
That's important , Because the following two statements are legal :
Why can a database treat a subquery as a table ? For a unified understanding of these concepts , It is necessary for us to understand the query content abstractly : Any query location is one or more records .
such as test This table , Obviously multiple records ( Of course, only one line is a record ), and SELECT pv FROM test It is also multiple records , But because FROM You can query any number of records later , So both grammars support .
Not only is FROM It can be associated with one or more records , even to the extent that SELECT、GROUP BY、WHERE、HAVING After that, you can follow multiple records , We'll talk about that later .
Speaking of this , It's easy to understand the variants of subquery , For example, we can use... In subqueries WHERE or GROUP BY wait , Because anyway , As long as the query result is multiple records :
This example has some business implications . Subqueries are executed from the inside out , So let's first look at the internal logic : Grouped by city , Filter out total GDP Population breakdown of all regions with more than 10000 people . The outer query adds up the population , So you can compare each GDP More than 10000 areas , Total population and total GDP What are the differences , It is convenient to compare these key cities .
But this example still looks unnatural , Because we don't have to write complex queries , In fact, simple queries are also equivalent :
Then why do you want to do this ? Because the real use of complex queries is not here .
View
Because of the existence of subqueries , We can extract variables in a similar way , Extract subqueries , The extracted abstraction is the view :
The advantage of this is , This view can be used by multiple SQL Statement reuse , Not only is maintainability better , When executing, you only need to query once .
It should be noted that ,SELECT You can use any view , but INSERT、DELETE、UPDATE When used for views , The view needs to meet the following conditions :
- not used DISTINCT duplicate removal .
- FROM Single table .
- not used GROUP BY and HAVING.
Because the above modes will cause the view to become aggregated data , It is not convenient to do operations other than checking .
Another knowledge point is materialized view , That is to use MATERIALIZED Description view :
This view will drop , Why support this feature ? Because the normal view is used as a temporary table , Unable to use optimization means such as index , Low query performance , Therefore, materialized view is a common means of performance optimization .
When it comes to performance optimization , There are also some common ideas , That is, allocate the complexity of reading to writing , For example, aggregate new tables in advance and drop them, or make changes to CASE Statements are solidified into fields, etc , Don't start here .
Scalar subquery
It says ,WHERE You can also follow the sub query , such as :
In this way, you can find gdp Cities larger than average .
Then why can't you just write that ?
It looks good , But in fact, in the first article, we introduced ,WHERE Cannot query with aggregate , Because this will aggregate the entire parent query . Then why can subqueries ? Because subqueries aggregate subqueries , The parent query is not aggregated , That's why it's in line with our intention .
So the inappropriate part of the above example is , Use... Directly in the current query avg(gdp) Can lead to aggregation , And we don't want to aggregate the current query , But we have to get the average through aggregation GDP, So we need to use sub query !
Looking back , Why is this section called scalar quantum query ? A scalar is a single value , because avg(gdp) The aggregate has only one value , therefore WHERE You can use it as a single value . conversely , If the subquery does not use an aggregate function , or GROUP BY grouping , Then it can't be used WHERE > This grammar , But you can use WHERE IN, This involves thinking about single and multiple records , Let's move on to the next section .
Single and multiple records
When introducing scalar subquery, I talked about ,WHERE > The value of must be a single value . But in fact WHERE You can also return subquery results of multiple records , Just use reasonable conditional statements , such as IN:
The above example , Subqueries are grouped by city , And find each group GDP The biggest record , So if the data granularity is region , So we found every city GDP The biggest records , Then the parent query passes WHERE IN find gdp The plural result of coincidence , So in the end, each city will be the largest gdp The areas are listed .
But actually WHERE > Statements and complex query results will not report errors , But it doesn't make any sense , So we need to understand whether the query results are single or multiple , stay WHERE Choose the right conditions when judging .WHERE The syntax suitable for complex query results is :WHERE IN、WHERE SOME、WHERE ANY.
Associated subquery
The so-called associated sub query , That is, there is an association between parent-child queries , In that case , Subqueries must not be executed independently , After all, it is associated with the parent query , Therefore, the associated sub query is to execute the outer query first , Then execute the inner query . It should be noted that , Parent query for each row , Subqueries are executed once , Therefore, the performance is not high ( Of course SQL The sub query results with the same parameters will be cached ).
So what is this connection ? Associated with each row of parent query , Conditions for sub query execution . It may be a little convoluted to say so , for instance :
For this example , Want to find gdp Greater than the average by city gdp, For example, Beijing area is compared with Beijing , Shanghai area is compared according to Shanghai . But it's a pity that it won't work , Because the parent-child query has no association ,SQL I don't know to compare according to the same city , So just add one WHERE Conditions , It becomes an associated sub query :
It's every time you judge WHERE gdp > When the conditions , Recalculate subquery results , Limit the average to the same city , This meets the demand .
边栏推荐
- Type the URL to the web page display. What happened during this period?
- Doctoral Dissertation of the University of Toronto - training efficiency and robustness in deep learning
- 数据库优化
- Database transactions
- Observable, reliable: the first shot of cloudops series Salon of cloud automation operation and maintenance
- 最佳实践:优化Postgres查询性能(下)
- Leetcode 1381. 设计一个支持增量操作的栈
- Data intelligence enters the "deep water area", and data governance is the key
- Crontab's learning essays
- Redis cluster Series III
猜你喜欢
随机推荐
Pyhton crawls Baidu library text and writes it into word document
[required reading for high-quality products] sub query of Oracle database in Linux system
Safety is the last word, Volvo xc40 recharge
低代码开发平台是什么?为什么现在那么火?
BAIC makes a brand new pickup truck, which is safe and comfortable
Type the URL to the web page display. What happened during this period?
Postman 汉化教程(Postman中文版)
云原生安全指南: 从零开始学 Kubernetes 攻防
MASS幸运哈希游戏系统开发丨冲突解决方法(代码分析)
Leetcode 1381. 设计一个支持增量操作的栈
什么是堆栈?
Pfsense plus22.01 Chinese customized version release
字典树(复习)
ABAP-CL_OBJECT_COLLECTION工具类
MongoDB简介及典型应用场景
Ble Bluetooth module nrf518/nrf281/nrf528/nrf284 chip scheme comparison
[bug] there is an error uploading the picture (413 request entity too large)
UE4实现长按功能
As a software engineer, give advice to young people (Part 2)
CSDN skill tree experience and product analysis (1)









