【数据库摘要】5_Sql_IN

IN 操作符

IN 操作符同意您在 WHERE 子句中查找多个值。

SQL IN 语法

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);

IN 操作符实例

(使用Northwind样本数据库) SELECT * FROM Customers WHERE City IN ('Paris','London');

MongoDB 语法

db.collection.find( { type: { $in: [ 'food', 'snacks' ] } } )

EXISTS

NOT EXISTS,exists的使用方法跟in不一样,一般都须要和子表进行关联,并且关联时,须要用索引,这样就能够加高速度

exists是用来推断是否存在的,当exists(查询)中的查询存在结果时则返回真,否则返回假。not exists则相反。

in 是把外表和内表作hash 连接,而exists是对外表作loop循环,每次loop循环再对内表进行查询。一直以来觉得exists比in效率高的说法是不准确的。

假设查询的两个表大小相当,那么用in和exists区别不大。

假设两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in:

比如:表A(小表),表B(大表)

  • select * from A where cc in (select cc from B)效率低,用到了A表上cc列的索引;

  • select * from A where exists(select cc from B where cc=A.cc)效率高,用到了B表上cc列的索引。

  • select * from B where cc in (select cc from A)效率高,用到了B表上cc列的索引;

  • select * from B where exists(select cc from A where cc=B.cc)效率低,用到了A表上cc列的索引。

not in 和not exists假设查询语句使用了not in 那么内外表都进行全表扫描,没实用到索引;

而not extsts 的子查询依旧能用到表上的索引。所以不管那个表大,用not exists都比not in要快。


你也能够訪问http://txidol.github.io 获取很多其它的信息

原文地址:https://www.cnblogs.com/hrhguanli/p/3910159.html