当前位置:网站首页>Sub query of database performance series
Sub query of database performance series
2022-07-27 10:15:00 【Dotnet cross platform】
Preface

Speaking of databases , Presumably some friends will think , Database is not every day CRUD Do you ? As long as I master these tricks , It's nothing at all . Yes , In fact, I also agree with this view , For most applications , Only master these contents , Is competent for daily development work .
However, our program cannot always stay in the test environment , As the amount of production environment data increases , And the growth of user scale , There will be some performance problems in the database . So in the next period of time , We will learn some aspects of database performance optimization , I hope it can bring you some enlightenment and growth . today , Let's start with the most basic sub query .
summary

The definition of subquery itself is simple , Is a nested query . The most common example is that we have two tables students and classes, To simplify the description , Three paradigms are not followed here , The fields in the table are as follows :
sutdents
| id | stu_name | stu_age | class_id |
| 1 | Zhang San | 15 | 1002 |
| 2 | Li Si | 15 | 1001 |
| 3 | Wang Wu | 16 | 1002 |
| 4 | Zhu Liu | 14 | 1003 |
classes
| class_id | class_name |
| 1001 | Chinese language and literature |
| 1002 | mathematics |
| 1003 | English |
At this point, we want to inquire which students have chosen math class , You can use subqueries to find results :
SELECT stu_name FROM sutdents WHERE sutdents.class_id IN (SELECT class_id FROM classes WHERE class_name = ' mathematics ')It can be seen that , We used... Here IN Operator to correlate the results of subqueries , Familiar partners must know , There is also a way of sub query called EXISTS, Use as follows :
SELECT stu_name FROM sutdents s WHERE EXISTS (SELECT 1 FROM classes c WHERE s.class_id = c.class_id AND class_name = ' mathematics ')The query results of the two methods are consistent , We found out which students chose math :

But actually , The efficiency of these two sub queries is different in different cases , Now let's talk about the difference between these two methods .
What is? IN

Literally ,IN That is, the fields of the external table , Use the results of internal nested queries as conditions to query the required results . therefore , Use IN when , Nested subqueries can only be queried once , Here comes a concept , be called : Non-associative subqueries .
In our example above , The sub query will start from classes Find the course name in the table as “ mathematics ” Of id, At this time, the subquery is executed only once . Through the results of the query , That is, math class id Number , As the condition of external query , To find the final result .
What is? EXISTS

alike , seeing the name of a thing one thinks of its function ,EXISTS That is to say “ There is ”. in other words , When nesting queries , Information of external table , Need to exist in the result of internal table , Only then can the query result . therefore , Use EXISTS when , Nested subqueries will be queried multiple times , The number of times depends on the record entries of the external table , Finally, the corresponding result is returned to the external table , This concept is called : Associated subquery .
In the example above , The query statement will start from students Find the corresponding class_id, Then pass it to the internal sub query , Internal subqueries use this class_id Match , Go to classes Search the table to meet class_id and class_name by “ mathematics ” The record of , Then return to the external table . In the process , Only exactly matched records , Will present the final result .
How to optimize subqueries

It is often mentioned in many previous experiences and some articles , Optimize SQL sentence , Need to use EXISTS Instead of IN, You can achieve the effect . So is this sentence correct ?
Through today's learning , We now know , That's not quite true , Not entirely wrong . The root cause is , We already know IN and EXISTS Characteristics of , So the conclusion is as follows :
1、 If in a statement , Subquery external table A, The quantity is smaller than the table inside the sub query B, So at this time , Use EXISTS The efficiency of , Is greater than IN Of . This is because EXISTS Each query will cycle through the table A Data in , Then pass in the table B Match , In this case , Use EXISTS Fewer cycles , Fewer record entries need to be queried .
2、 conversely , If you subquery an external table A, The quantity is larger than the table inside the subquery B, So at this time , Use IN Will be more efficient . At this time to use IN You can narrow the range of records to be found , Final match table A Can reduce the size of records .
summary

Today we explain the concept of subquery and some simple usage , And some optimization methods . We can divide sub query into two modes: associated sub query and non associated sub query , They correspond to each other IN and EXISTS Usage of . Finally, when optimizing subqueries, we mentioned that which method to use depends on the size relationship between the outer table and the inner table , In fact, the focus of optimization is the principle of using small tables to drive large tables , Have you learned all these ?
In the next issue, we will continue to talk about how to optimize database performance from the perspective of database indexing , friends , See you next time !

Your praise and appreciation are the biggest driving force of my creation , Thank you for your support



official account :wacky I'm sorry
You know :wacky
边栏推荐
- Pyautogui realizes automatic office -rpa small case
- Stylegan paper notes + modify code to try 3D point cloud generation
- Matlab- draw superimposed ladder diagram and line diagram
- Food safety | are you still eating fermented rice noodles? Be careful these foods are poisonous!
- Shell operator, $((expression)) "or" $[expression], expr method, condition judgment, test condition, [condition], comparison between two integers, judgment according to file permission, judgment accor
- vs2019社区版下载教程(详细)
- WGAN、WGAN-GP、BigGAN
- LeetCode.1260. 二维网格迁移____原地暴力 / 降维+循环数组直接定位
- Review of in vivo detection
- 中高级试题」:MVCC 实现原理是什么?
猜你喜欢
![Shell function, system function, basename [string / pathname] [suffix] can be understood as taking the file name in the path, dirname file absolute path, and user-defined function](/img/3d/d7276d2010f1d77a3bd572cc66eced.png)
Shell function, system function, basename [string / pathname] [suffix] can be understood as taking the file name in the path, dirname file absolute path, and user-defined function

When I went to oppo for an interview, I got numb

pillow的原因ImportError: cannot import name ‘PILLOW_VERSION‘ from ‘PIL‘,如何安装pillow<7.0.0

Food safety | the more you eat junk food, the more you want to eat it? Please keep this common food calorimeter
![[SCM]源码管理 - perforce 分支的锁定](/img/c6/daead474a64a9a3c86dd140c097be0.jpg)
[SCM]源码管理 - perforce 分支的锁定

邮件服务器

ACL2021最佳论文出炉,来自字节跳动

Discussion on a problem

open3d库的安装,conda常用指令,导入open3d时报这个错误Solving environment: failed with initial frozen solve. Retrying w

Pygame: alien invasion
随机推荐
Why is redis so fast? Redis threading model and redis multithreading
3D人脸重建:Joint 3D Face Reconstruction and Dense Alignment with position Map Regression Network
Matlab-基于短时神经网络的声音分类
What happens if the MySQL disk is full? I really met you!
Shell流程控制(重点)、if 判断、case 语句、let用法、for 循环中有for (( 初始值;循环控制条件;变量变化 ))和for 变量 in 值 1 值 2 值 3… 、while 循环
NFS 服务器的搭建
Acl2021 best paper released, from ByteDance
Case of burr (bulge) notch (depression) detection of circular workpiece
Interview JD T5, was pressed on the ground friction, who knows what I experienced?
FSM onehot answer record
hdu5288(OO’s Sequence)
RobotFramework+Eclispe环境安装篇
Matlab-创建 MATLAB的logo
When I went to oppo for an interview, I got numb
hdu5289(Assignment)
About new_ Online_ Judge_ 1081_ Thoughts on Goldbach's conjecture
Huawei switch dual uplink networking smart Link Configuration Guide
如何创建一个带诊断工具的.NET镜像
Pygame: alien invasion
并发之park与unpark说明