SQL中的Exist操作
exists用于檢查一個(gè)子查詢是否至少會(huì)返回一行數(shù)據(jù)(即檢測(cè)行的存在),返回值為true或false。
語(yǔ)法: exists subquery
參數(shù): subquery是一個(gè)受限的select語(yǔ)句(不允許有compute子句和into關(guān)鍵字),該語(yǔ)句返回一個(gè)結(jié)果集。
結(jié)果類型: boolean類型——如果子查詢包含行,則返回true,否則返回false,即言:exists根據(jù)subquery的結(jié)果集是否為空來(lái)返回一個(gè)布爾值——如果不為空則返回true,否則返回false。
以例子說(shuō)明其使用方法:
table1table2
id class_nameid name class_id
01一年級(jí) 01 張三01
02二年級(jí) 02 李四02
03三年級(jí) 04 王五04
1、在子查詢中使用NULL仍然返回結(jié)果集:select * from table1 where exists(select null),該條sql語(yǔ)句等同于:select * from table1,其查詢結(jié)果為:
id class_name
01一年級(jí)
02二年級(jí)
03三年級(jí)
2、select t1.id,t1.class_name from table1 t1 where exists (select * from table2 t2 where t2.class_id = t1.id),該條sql語(yǔ)句等同于:select t1.id,t1.class_name from table1 t1 where t1.id in (select t2.class_id from table2 t2 where t2.class_id = t1.id),其查詢的結(jié)果為:
id class_name
01一年級(jí)
02二年級(jí)
其查詢過(guò)程為:
select t1.id,t1.class_name from table1 t1 where exists (select * from table2 t2 where t2.class_id = '01')
---> select * from table2 t2 where t2.class_id = '01'有數(shù)據(jù)存在,所以exists返回true;
select t1.id,t1.class_name from table1 t1 where exists (select * from table2 t2 where t2.class_id = '02')
---> select * from table2 t2 where t2.class_id = '02'有數(shù)據(jù)存在,所以exists返回true;
select t1.id,t1.class_name from table1 t1 where exists (select * from table2 t2 where t2.class_id = '03')
---> select * from table2 t2 where t2.class_id = '03'沒(méi)有數(shù)據(jù)存在,所以exists返回false;
這種執(zhí)行過(guò)程可以通俗的理解為:將外查詢表的每一行,代入內(nèi)查詢作為檢驗(yàn),如果內(nèi)查詢返回的結(jié)果取非空值,則exists子句返回true,這一行可作為外查詢的結(jié)果行,否則不能作為結(jié)果。
分析器會(huì)先看語(yǔ)句的第一個(gè)詞,當(dāng)它發(fā)現(xiàn)第一個(gè)詞是select關(guān)鍵字的時(shí)候,它會(huì)跳到from關(guān)鍵字,然后通過(guò)from關(guān)鍵字找到表名并把表裝入內(nèi)存,接著是找where關(guān)鍵字,如果找不到則返回到select找字段解析,如果找到where,則分析其中的條件,完成后再回到select分析字段,最后形成一張?zhí)摫怼?br />where關(guān)鍵字后面的是條件表達(dá)式,條件表達(dá)式計(jì)算完成后,會(huì)有一個(gè)返回值,即非0或0,非0即為真(true),0即為假(false)。如果為正則執(zhí)行select語(yǔ)句,否則不執(zhí)行select語(yǔ)句。
分析器先找到關(guān)鍵字select,然后跳到from關(guān)鍵字,將該關(guān)鍵字后面的表導(dǎo)入內(nèi)存,并通過(guò)指針找到第一條記錄,接著找到where關(guān)鍵字計(jì)算它的條件表達(dá)式,如果為真那么把這條記錄裝到一個(gè)虛表當(dāng)中,指針再指向下一條記錄。如果為假那么指針直接指向下一條記錄,而不進(jìn)行其它操作。一直檢索完整個(gè)表,并把檢索出來(lái)的虛擬表返回給用戶。exists是條件表達(dá)式的一部分,它也有一個(gè)返回值(true或false)。
在插入記錄前,需要檢查這條記錄是否已經(jīng)存在,只有當(dāng)記錄不存在時(shí)才執(zhí)行插入操作,可以通過(guò)使用EXISTS條件句防止插入重復(fù)記錄。
insert into table1 (id,class_name) values ('03','四年級(jí)') where not exists (select * from table1 where table1 = '03')
exists與in的區(qū)別:
1、in引導(dǎo)的子句只能返回一個(gè)字段,exists子句可以有多個(gè)字段;
2、通常情況下采用exists要比in效率高,因?yàn)閕n不走索引,但要但要具體情況具體分析:in適合于外表大而內(nèi)表小的情況;exists適合于外表小而內(nèi)表大的情況。
轉(zhuǎn)載于:https://www.cnblogs.com/jpit/p/8317176.html
總結(jié)
以上是生活随笔為你收集整理的SQL中的Exist操作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 借助Docker单机秒开数十万TCP连接
- 下一篇: ssm框架的整合搭建(一)