当前位置:网站首页>Record the learning record of the exists keyword once
Record the learning record of the exists keyword once
2022-06-25 22:46:00 【The stars are falling】

CREATE TABLE `t_class` (`id` int unsigned NOT NULL AUTO_INCREMENT,`class_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT '' COMMENT ' Class name ',PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT=' Class name table ';
CREATE TABLE `t_student` (`id` int unsigned NOT NULL AUTO_INCREMENT,`user_name` varchar(30) 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=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT=' Student list ';
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 ',PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT=' Class student association table ';
INSERT INTO stu.t_student (user_name,age) VALUES(' Zhang Yibo ',18),(' Lixiaorui ',19),(' Liulengshuang ',18),(' Zhaoyuzhen ',17),(' Liuyuandie ',19),(' Yingyan ',19),(' Wanqiu ',20),(' Liugaomin ',19),(' Wangkunxiong ',20),(' Zhaoxingpeng ',19);INSERT INTO stu.t_student (user_name,age) VALUES(' Gaokunhui ',18),(' Hao Lei ',18),(' Wangxiaofeng ',19);
INSERT INTO stu.t_class (class_name) VALUES(' Class 1, Department of economics and trade '),(' Class two, Department of medicine '),(' Foreign languages A class '),(' Class 3, journalism department '),(' Class 1, Department of landscape tourism '),(' Class one, computer department ');
INSERT INTO stu.t_class_student (student_id,class_id) VALUES(1,1),(2,1),(3,2),(4,2),(5,2),(6,2),(7,3),(8,3),(9,4),(10,4);INSERT INTO stu.t_class_student (student_id,class_id) VALUES(13,6);
select id, user_name as userName, agefrom stu.t_student as swhere exists ( select student_id from stu.t_class_student where student_id = s.id);
A list of students who did not report to the department class :
select s.id, s.user_name as userName, s.agefrom stu.t_student as swhere not exists ( select student_id from stu.t_class_student where student_id = s.id);
A list of the registered students of class 2 of the Department of medicine :
select s.id, s.user_name as userName, s.agefrom stu.t_student as swhere exists ( select student_id from stu.t_class_student where student_id = s.id and class_id = 2);
Class 1, Department of economics and trade and Foreign languages A A list of students who have registered for the class :
select s.id, s.user_name as userName, s.agefrom stu.t_student as swhere exists ( select student_id from stu.t_class_student where student_id = s.id and class_id in (1, 3));
A list of students in all departments and classes that have registered :
select s.id, s.user_name as userName, s.agefrom stu.t_student as swhere exists ( select student_id from stu.t_class_student where 1 = 1);
Class 2, Department of medicine and older than 18 A list of students who have registered at the age of :
select s.id, s.user_name as userName, s.agefrom stu.t_student as swhere s.age > 18 and exists ( select student_id from stu.t_class_student where student_id = s.id and class_id = 2);
【exists and in Comparison between 】
Execute the process :
Let's start with keywords in, It requires that the query result meet in The conditions in the following brackets , such as id、status etc. . It's going to put it first in Subquery in the following slogan sql After execution , Then, according to the results obtained, execute the previous master sql.
This is similar to the backflow of river water . Such as heavy rainfall , This leads to an increase in the amount of river water nearby , Because the elevation of the ponding road surface is lower than the elevation of the river water level , The river pours back into the storm sewer , Then the road area water is formed . So I call this method of execution " Backflow execution method ".
and exists Just the opposite , It's sequential execution , After execution exists Ahead sql After getting the results , Take the initiative and exists Subqueries in sql To match , Only successfully matched data can be returned to the console .
EXPLAIN Explanation of columns :
table: Show which table this row's data is about
type: This is an important column , Shows what type of connection is used . The best to worst connection type is const、eq_reg、ref、range、 indexhe and ALL
possible_keys: Show the indexes that may be applied to this table . If it is empty , There is no possible index . Can be related to the domain from WHERE Choose an appropriate statement
key: Actual index used . If NULL, No index is used . In rare cases ,MYSQL Will choose indexes that are not optimized enough . In this case , Can be in SELECT Use in statement USE INDEX(indexname) To force the use of an index or IGNORE INDEX(indexname) Mandatory MYSQL Ignore the index
key_len: Length of index used . Without losing accuracy , The shorter the length, the better
ref: Shows which column of the index is used , If possible , It's a constant
rows:MYSQL The number of rows that must be checked to return the requested data
Extra: About MYSQL How to parse the extra information of the query . The bad example is Using temporary and Using filesort, Meaning MYSQL Index can't be used at all , The result is that the retrieval will be slow
Index usage :
( One ) Query the students who have registered in all departments and classes :
explain select s.id, s.user_name as userName, s.agefrom stu.t_student as s where s.id in (select id from stu.t_class_student tcs);
Subqueries use indexes ,in Not used
explain select id, user_name as userName, agefrom stu.t_student as swhere exists ( select student_id from stu.t_class_student where student_id = s.id);
Subqueries use indexes , And the outer layer sqlexists Index is not used
( Two ) Check the status of students who have not registered in all departments :
explain select s.id, s.user_name as userName, s.agefrom stu.t_student as s where s.id not in (select id from stu.t_class_student tcs);
Similarly, subqueries use indexes ,not in Keyword is not used in index
explain select id, user_name as userName, agefrom stu.t_student as swhere not exists ( select student_id from stu.t_class_student where student_id = s.id);
Use not exists The same is true of : Subqueries use indexes ,not in Keyword is not used in index , Full scan of walking
【 Conclusion 】
Crossing mountains and mountains is only for one meeting , Go all out for one change . The answer is in tears , Also condensed in sweat 、 Senses and mind . There's always one thing to live elsewhere , You will strengthen your love .
边栏推荐
- 2022爱分析· IT运维厂商全景报告
- CVPR2022教程 | 马里兰大学《机器学习遥感处理:农业与粮食安全》教程
- How to use the find command
- This 110 year old "longevity" enterprise has been planning for the next century
- Wpewebkit debugging MSE playback
- Evaluate the generalization performance of models and build integrated models using out of pocket prediction (oof)
- Lecture 14 of the Blue Bridge Cup -- number theory [example]
- OSPF - detailed explanation of GRE tunnel (including configuration command)
- NARI radar's IPO meeting: it plans to raise nearly 1billion yuan. Bao Xiaojun and his wife are Canadians
- Audio orchestrator: orchestrate immersive interactive audio using multiple devices
猜你喜欢
2022-2028 global cloud based remote browser isolation industry research and trend analysis report
【WPF】CAD工程图纸转WPF可直接使用的xaml代码技巧
Summary of basic knowledge of neural network
Jingwei Hengrun is registered through the science and Innovation Board: it plans to raise 5billion yuan, with a 9-month revenue of 2.1 billion yuan
圖解棧幀運行過程
Will neuvector be the next popular cloud native security artifact?
Lecture 14 of the Blue Bridge Cup -- number theory [exercises]
Tiger Dao VC products are officially launched, a powerful supplement to seektiger ecology
Talk about adapter mode
简单好用的缓存库 gcache
随机推荐
2022-2028 global TFT touch screen industry research and trend analysis report
[intensive lecture] 2022 PHP intermediate and advanced interview questions (II)
Audio orchestrator: orchestrate immersive interactive audio using multiple devices
Jz-064- maximum value of sliding window
Obsidian basic tutorial
OSPF - detailed explanation of GRE tunnel (including configuration command)
Tlog helps Pangu framework realize microservice link log tracking
图解栈帧运行过程
Obsidian基础教程
Raspberry PI (bullseye) replacement method of Alibaba cloud source
Privatization lightweight continuous integration deployment scheme -- 03 deployment of Web services (Part 2)
Use of local stack in flask
【WPF】CAD工程图纸转WPF可直接使用的xaml代码技巧
Report on development status and prospects of global and Chinese coating industry strategic planning proposal 2022-2028
Introduction to HLS content diversion and insert advertising specification
剖析虚幻渲染体系(16)- 图形驱动的秘密
Evaluate the generalization performance of models and build integrated models using out of pocket prediction (oof)
2022giao考游记
Pycharm 2022.1 EAP 2 release
Research and Analysis on the current situation of Chinese acne drug market and forecast report on its development prospect (2022)