sql优化

一.mysql 优化之is null ,is not null 索引使用测试

  1.创建t_user表,在name字段创建索引,且name字段不能为null。

  EXPLAIN select * from t_user where name is not null;//不使用索引;

  EXPLAIN select * from t_user where name is null;//不使用索引;

  EXPLAIN select name from t_user where name is not null;//使用索引;

  EXPLAIN select name from t_user where name is null;//不使用索引;

  EXPLAIN select name ,age from t_user where name is not null;//不使用索引

  EXPLAIN select name,age from t_user where name is null;//不使用索引

  结论:当索引字段不可以为null时,只有使用is not null 并且返回的结果集中制包含索引字段的时,才使用索引。

  2.创建t_user表,在name字段创建索引,且name字段可以为null.

  EXPLAIN select * from t_user where name is not null;//不使用索引;

  EXPLAIN select * from t_user where name is null;//使用索引;

  EXPLAIN select name from t_user where name is not null;//使用索引;

  EXPLAIN select name from t_user where name is null;//使用索引;

  EXPLAIN select name ,age from t_user where name is not null;//不使用索引

  EXPLAIN select name,age from t_user where name is null;//使用索引

  结论:当索引字段可以为null,使用is null 不影响覆盖索引,但是使用is not null只有完全返回索引字段时才会使用到索引。

2.in 和exists效率问题

  in 是把外表和内表作hash连接,而exists是对外表作loop循环,每次loop循环再对内标进行查询。

  一直以来认为exists 比in效率高的说法不准确的。

  如果查询的两个表大小相当,那么用in和exists差别不大。

  如果两个表中一个表笑,一个是大表,则子查询表大的用exists,反之用in;

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

  1.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.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 exists 的子查询依然能用到表上的索引;

  

 

sql优化

上一篇:vc sqlite


下一篇:How to import data from Oracle into PostgreSQL(转)