Mysql-sql查询技巧分析

一、索引能不能为空

  提前建立 email 为索引

1、explain select * from myshop.user where email is null;

  输出

   可以看到用到索引

2、explain select * from myshop.user where email = 'test';

  输出

   可以看到用到索引

3、explain select * from myshop.user where email is not null;

  输出

  当表有大部分数据,查找不为空的索引就失效。

二、函数计算会不会使用索引

1、

  

   输出

2、

  

 输出

  

  改为以下

  

 输出,避免使用函数

  

没有使用函数,则用了索引

三、类型不一致,可以用索引吗

1、add_time 是数值,‘1591025358’ 是字符串;

  

 输出

  

 因为优化器自动优化的原因,因此可以用索引

四、where 顺序

  提前给表做的以下索引

1、

  看最左前缀

  可以顺序不一样,但是不能少

五、union 要代替 or 语句吗

  union 比 or 消耗比较小,如下,看具体情况

  

   如果有较大的数据就拆为 union

六、exist 和 in 

  exist 比较快

原文地址:https://www.cnblogs.com/Jomini/p/14116526.html