美文网首页
Mysql | in与exists及not in与not exi

Mysql | in与exists及not in与not exi

作者: 七喜丶 | 来源:发表于2022-08-02 15:01 被阅读0次

    对于in和exists的语句改写:

    in==> select * from system_log where user_id in (select id from user);
     
    exists==> select system_log.* from system_log where exists 
    (select 1 from user where system_log.id= user.id);
    

    注意:select 1 from的作用
    1、select 1 from mytable;select anycol (目的表集合中的任意一行) from mytable; select * from mytable;作用上来说是没有差别的,都是查看是否有记录。
    2、 select 1 from 中的1是一常量,查到的所有行的值都是它,但从效率上说:1>anycol>*,因为不用查字典表。有数据就返回1,没数据返回null

    一、使用区别

    exists,not exists一般都是与子查询一起使用;in 或 not in可以与子查询一起使用,也可以直接in (a,b.......)

    二、索引区别

    exists:针对子查询的表使用索引
    not exists:对主子查询都会使用索引
    in:与子查询一起使用时候,只能针对主查询使用索引
    not in:不会使用任何索引

    注意:认为exists比in效率高的说法是不准确的。

    二、in与exists区别
    1. in是把外表和内表作hash连接,而exists是对外表作loop循环,每次loop循环在对内表进行查询
    2. 如果查询的两个表大小相当,那么用in和exists差别不大
    3. 如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in

    例如
    1、表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列的索引
    

    2、表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列的索引
    

    not in 和not exists如果查询语句使用了not in 那么内外表都进行全表扫描,没有用到索引;而not extsts 的子查询依然能用到表上的索引。所以无论那个表大,用not exists都比not in要快。

    3、exists与in都可以实现一个目的:过滤数据

    select count(1) from t1;--160W
    select count(1) from t2; --90W
    SELECT count(1) FROM t1 a WHERE EXISTS (SELECT accountid FROM t2 b
    WHERE a.keyid = b.keyid AND a.ideaid = b.ideaid);
    

    主大子小,不适合使用exists,因为exists只会利用子表t2的复合索引keyid+ideaid,而子表内容要小与主表,主表由于无法使用索引,查询效率低下

    select count(1) from t1 a where accountid in (SELECT accountid
    FROM t2 b
    WHERE a.keyid = b.keyid AND a.ideaid = b.ideaid);
    

    主大子小,适合用in,因为in只会使用主表t1里面的复合主键keyid-ideaid,在主表大于子表的情况下,会很好的利用主表的索引.
    --后二条sql的执行结果都是一样的.说明exist与in在用法上可以达到一个目的,不同的地方是
    --1.性能的考虑此时就按子表大主表小用exist,子表小主表大用in的原则就可以.
    --2.写法的不同, exist的where条件是: "...... where exist (..... where a.id=b.id)"
    --in的where条件是: " ...... where id in ( select id .... where a.id=b.id)"

    4、exists的原理
    exists做为where 条件时,是先对where 前的主查询询进行查询,然后用主查询的结果一个一个的代入exists的查询进行判断,如果为真则输出当前这一条主查询的结果,否则不输出

    相关文章

      网友评论

          本文标题:Mysql | in与exists及not in与not exi

          本文链接:https://www.haomeiwen.com/subject/vagdwrtx.html