当前位置:网站首页>Detailed explanation of the usage of exists in MySQL
Detailed explanation of the usage of exists in MySQL
2022-07-29 00:13:00 【m0_ fifty-four million eight hundred and sixty-one thousand six】
Preface
In daily development , use mysql When querying , There is a relatively rare keyword exists, Let's learn about this today
exists This sql Usage of keywords , In this way, when you encounter some specific business scenarios in your work, you can have more diversified solutions
Grammar explanation
grammar
SELECT column1 FROM t1 WHERE [conditions] and EXISTS (SELECT * FROM t2 );
explain
- The subquery in parentheses will not return the specific queried data , It's just going back to true perhaps false, If the outer layer sql If the field of exists in the subquery, it returns true, Returns if it does not exist false
- Even if the query result of sub query is null, As long as the corresponding field exists , The subquery returns true, Here are specific examples
Execution process
1、 First, make an outer query , In the table t1 Query the qualified column1
2、 Next, make an inner query , The column1 Table brought into the inner layer t2 Query in ,
3、 If the inner table t2 Meet query criteria , Then return to true, This data is reserved
4、 If the inner table t2 The query condition is not satisfied , Then return to false, Then delete the data
5、 Finally, all the qualified data in the outer layer will be returned
Post a link ,mysql Official instructions for this order : https://dev.mysql.com/doc/refman/8.0/en/exists-and-not-exists-subqueries.html; Those who like to read the original English description can come here to have a look
Use cases
Environmental preparation
?? mysql edition : 8.0.28
?? Database table design :
Student list : t_student
CREATE TABLE
t_student
(id
int unsigned NOT NULL AUTO_INCREMENT,name
varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT ‘’ COMMENT ‘ The student's name ’,age
int NOT NULL COMMENT ‘ Age ’,
PRIMARY KEY (id
)
) ENGINE=InnoDB AUTO_INCREMENT=37 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT=‘ Student list ’;
Import some data
INSERT INTO `t_student` (`id`, `name`, `age`)
VALUES
(1, ' Xiao Zhang ', 10),
(2, 'chenille', 13),
(3, ' Xiao Wang ', 15),
(4, ' millet ', 11),
(5, 'dong', 13),
(6, 'xi', 12),
(7, 'chenille', 13),
(8, ' Xiao Wang's place ', 15),
(9, ' Mi Lai ', 11),
(10, 'dong', 13),
(11, ' ha-ha ', 12),
(12, 'chenille', 13),
(13, ' Xiao zhao ', 15),
(14, ' millet -0', 11),
(15, 'bei', 13),
(16, 'xi-xx', 12),
(17, 'chenille', 13),
(18, ' Xiao Wang -hehe', 15),
(19, ' millet -qian', 11),
(20, 'dong', 13),
(21, 'xi', 12),
(22, 'chenille', 13),
(23, ' Xiao Wang -1', 15),
(24, ' millet -2', 11),
(25, 'dong-3', 13),
(26, 'xi-0', 12),
(27, 'chenille-4', 13),
(28, ' Xiao Wang -4', 15),
(29, ' millet -7', 11),
(30, 'dong-1', 13),
(31, 'xi-5', 12),
(32, ' brave troops ', 10),
(33, ' advanced in years ', 12),
(34, ' feastful ', 9),
(35, ' dragon ', 13),
(36, ' Qingniu ', 12);
Class student list :t_class_student
CREATE TABLE
t_class_student
(id
int unsigned NOT NULL AUTO_INCREMENT,student_id
int NOT NULL COMMENT ‘ Student ID’,class_id
int NOT NULL COMMENT ‘ Class number ’,class_name
varchar(100) DEFAULT ‘’ COMMENT ‘ Class name ’,
PRIMARY KEY (id
)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT=‘ Class student list ’;
Import some data
INSERT INTO `t_class_student` (`id`, `student_id`, `class_id`, `class_name`)
VALUES
(1, 1, 1, ' In grade one 1 class '),
(2, 2, 1, ' In grade one 1 class '),
(3, 3, 1, ' In grade one 1 class '),
(4, 4, 1, ' In grade one 1 class '),
(5, 5, 1, ' In grade one 1 class '),
(6, 6, 1, ' In grade one 1 class '),
(7, 7, 1, ' In grade one 1 class '),
(8, 8, 1, ' In grade one 1 class '),
(9, 9, 1, ' In grade one 1 class '),
(10, 10, 1, ' In grade one 1 class '),
(11, 11, 2, ' In grade one 2 class '),
(12, 12, 2, ' In grade one 2 class '),
(13, 13, 2, ' In grade one 2 class '),
(14, 14, 2, ' In grade one 2 class '),
(15, 15, 2, ' In grade one 2 class '),
(16, 16, 2, ' In grade one 2 class '),
(17, 17, 2, ' In grade one 2 class '),
(18, 18, 2, ' In grade one 2 class '),
(19, 19, 2, ' In grade one 2 class '),
(20, 20, 2, ' In grade one 2 class '),
(21, 21, 3, ' second grade 2 class '),
(22, 22, 3, ' second grade 2 class '),
(23, 23, 3, ' second grade 2 class '),
(24, 24, 3, ' second grade 2 class '),
(25, 25, 3, ' second grade 2 class '),
(26, 26, 3, ' second grade 2 class '),
(27, 27, 3, ' second grade 2 class '),
(28, 28, 3, ' second grade 2 class '),
(29, 29, 3, ' second grade 2 class '),
(30, 30, 3, ' second grade 2 class '),
(31, 31, 4, ' Third grade 1 class ');
(32, 32, 4, null);
Common query
List of students assigned to class ??
select * from t_student as s where exists (select student_id from t_class_student where student_id = s.id);
List of students not assigned to class ??
select * from t_student as s where not exists (select student_id from t_class_student where student_id = s.id);
Already allocated Third grade 1 class List of students ??
select * from t_student as s where exists (select student_id from t_class_student where student_id = s.id and class_id = 4);
Already allocated And the class is In grade one 1 class and In grade one 2 class List of students ??
select * from t_student as s where exists (select student_id from t_class_student where student_id = s.id and class_id in (1, 2) );
The queried fields are null, But the result returned by the subquery is true ??
select * from t_student as s where exists (select class_name from t_class_student where student_id = s.id and class_id = 4);
Check the list of all students ??
select * from t_student as s where exists (select student_id from t_class_student where 1=1);
Already allocated Third grade 1 class And older than 10 Year old student list ??
select * from t_student as s where age > 10 and exists (select student_id from t_class_student where student_id = s.id and class_id = 4);
exists And in Efficiency comparison of
In fact, the above queries can also be through in Keyword to implement , Now let's write in Keyword corresponding query statement ,
adopt in Realize the student list of assigned classes ??
select * from t_student as s where id in (select student_id from t_class_student where student_id = s.id);
adopt in Realize the list of students in unassigned classes ??
select * from t_student as s where id not in (select student_id from t_class_student where student_id = s.id);
Now let's analyze which of these two keywords is more efficient ?
Circular nested query execution principle
?? Cycle from outside to inside , The outer loop is executed once , The inner loop needs to be executed completely once , After the inner layer is executed, the execution result is returned , The outer loop continues , Until the outer loop is fully executed
Circular optimization strategy
?? With the above description of the implementation principle , We understand a truth : The number of cycles in the inner layer will not affect the number of cycles in the outer layer , The number of cycles in the outer layer will directly affect the number of cycles in the inner layer , Every time the outer layer circulates , The inner loop needs more than one complete loop , So our optimization goal is to minimize the number of cycles in the outer layer , In conclusion : Small tables drive large tables . A small watch is an outer loop , The big watch is the inner loop , That is to minimize the number of outer cycles
exists and in The difference between query principles
?? exists : First, make a circular query , Put the query results into exists Condition validation in subquery of , Determines whether the outer query data is retained
?? in : First query the internal table , The query results of the inner table are provided as conditions to the outer query statements for comparison
Conclusion
Through the above optimization strategy analysis and exists and in Analysis of query principle , Combining these two pieces of content actually leads to a conclusion we want :
- Outer watch , Inner big table ( Or will sql From left to origin : Small watch on the left , Big watch on the right ): exists Than in The high efficiency
- Outer big watch , Inner small table ( Or will sql From left to origin : Big watch on the left , Small watch on the right ): in Than exists The high efficiency
- Reference material
https://www.bilibili.com/video/BV1V64y1q7yispm_id_from=333.337.search-card.all.click
summary
Above, we briefly introduce one that we seldom use exists Key words of , Through some examples , You can also basically understand how to use it , In the future daily work , When we encounter some query problems , At this time, there are more diversified options , I hope this article will help you , thank you
边栏推荐
猜你喜欢
【微服务】Nacos集群搭建以及加载文件配置
Interpretation of ISO 13400 (doip) standard
Compilation principle research study topic 2 -- recursive descent syntax analysis design principle and Implementation
有效供应链管理的八大绩效分析指标(上)
Real time data warehouse: Netease strictly selects the practice of real-time data warehouse based on Flink
【C】atoi和offsetof的介绍和模拟实现
ISO 13400(DoIP)标准解读
Es6操作教程
Leetcode61. rotating linked list
Web系统常见安全漏洞介绍及解决方案-CSRF攻击
随机推荐
How NAT configures address translation
@Detailed explanation of the use of transactional annotation
【TA-霜狼_may-《百人计划》】图形3.6 纹理压缩——包体瘦身术
Eye of depth (18) -- partial derivative
laptop外接显示器
Leetcode62. 不同路径
Compose 的声明式代码如此简洁?
双重for循环优化
Leetcode64. 最小路径和
【小程序项目开发 -- 京东商城】uni-app 商品分类页面(上)
How can Plato obtain premium income through elephant swap in a bear market?
Powercli VMware vCenter deploys conventional new VMS in batch through self built PXE server with one click
Plato farm is expected to further expand its ecosystem through elephant swap
mysql中exists的用法详解
IDEA报错Error running ‘Application‘ Command line is too long解决方案
GhostNets on Heterogeneous Devices via Cheap Operations
Leetcode60. permutation sequence
Leetcode60. 排列序列
Linux之yum安装MySQL
Concurrency in go