網站首頁 編程語言 正文
現有:班級表(A_CLASS)
學生表( STUDENT)
注:學生表(STUDENT)的classId關聯班級表(A_CLASS)的主鍵ID
代碼:
select * from STUDENT s WHERE exists (select 1 from A_ClASS c where s.CLASS_ID=c.ID)
結果
【exists語句的執行順序如下】:
1.首先會執行外循環(select * from student
)
2.外循環返回的結果每一行都會拿著去內層循環執行(此時注意,內層也是循環查詢的)
ps:select * from student
查詢的為 (c1,c1,c2,c3);此時執行順序應該是(
第一次:select* from A_CLASS where c1=c1
,第二次:select* from A_CLASS where c1=c2
,
第三次:select* from A_CLASS where c1=c1
,第四次:select* from A_CLASS where c1=c2
,
第五次:select* from A_CLASS where c2=c1
,第六次:select* from A_CLASS where c2=c2
,
第七次:select* from A_CLASS where c3=c1
,第八次:select* from A_CLASS where c3=c2)
注意:此時的內層子查詢如果為true,則直接返回不會再繼續執行本次循環;
綜上所述:第二次和第四次是不會被執行的;? 第一次和第三次還有第六次是符合條件的;
所以?STUDENT表中CLASS_ID字段為(c1,c2)的數據都會被查詢出來;
如果將 上述語句的=換成!=會是什么效果?
select * from STUDENT s WHERE exists (select 1 from A_ClASS c where s.CLASS_ID!=c.ID)
結果如果所示:?
具體分析一下:此時的執行應該和第一次一模一樣也是循環8次分別為:
第一次:select* from A_CLASS where c1!=c1
,第二次:select* from A_CLASS where c1!=c2
,
第三次:select* from A_CLASS where c1!=c1
,第四次:select* from A_CLASS where c1!=c2
,
第五次:select* from A_CLASS where c2!=c1
,第六次:select* from A_CLASS where c2!=c2
,
第七次:select* from A_CLASS where c3!=c1
,第八次:select* from A_CLASS where c3!=c2
但是=換成了!=;這次是第六次和第八次沒有被執行,其余的全被執行,s.CLASS_ID涉及到(c1,c2,c3)并且語句都返回了true;
所以STUDENT表中CLASS_ID字段為(c1,c2,c3)的數據都會被查詢出來;
附:exists與in比較
in的用法相信大家很好理解。
select * from table_name where col_name [not] in(子查詢);
- 先運行子查詢,生成結果集
- 再運行外查詢時,判斷col_name在不在子查詢里,在的話則返回該行,不在則不返回。
- col_name的列數和子查詢的列數要相對應
當外大子小時,即查詢的內容很大時,判斷次數少,in優于exist【子查詢小用in】
當外小子大時,即查詢內容很小時,代入次數少,exists優于in【子查詢大用exists】
總結:
1.exists執行外循環后,會拿著外循環的值,去內層查詢,如果查詢到就直接返回true,并且終止本次循環,如果是false,則會一直執行,直至循環完成還為false,則本次內循環不符合條件;
2.內層的判斷條件不要寫!=;查詢的結果會不盡人意;
原文鏈接:https://blog.csdn.net/ibhjvbg/article/details/123344265
相關推薦
- 2022-08-07 C++文件的數據寫入和文件的數據讀取的方法實現_C 語言
- 2022-09-29 利用LyScript實現應用層鉤子掃描器_python
- 2022-11-09 LyScript實現Hook隱藏調試器的方法詳解_python
- 2023-06-19 scrapy?遠程登錄控制臺的實現_python
- 2022-11-13 linux?shell腳本學習指南_linux shell
- 2023-02-14 C++關于字符的接收與輸出操作示例_C 語言
- 2022-09-06 Golang實現http重定向https_Golang
- 2024-04-05 docker部署mongodb
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支