会造成全表扫描的SQL语句及应对措施

全表扫描时,会造成CPU和内存的额外消耗,甚至会导致服务器崩溃。所以我们应避免。

1、左模糊查询Like %XXX%

如:select account from member where nickname like ‘%XXX%’
或者 select account from member where nickname like ‘%XXX’
建议使用select account from member where nickname like ‘XXX%’

2、使用null做为判断条件

如:select account from member where nickname = null;
建议在设计字段时尽量将字段的默认值设为0,改为select account where nickname = 0;

3、对字段进行函数操作

如:select account where salary * 0.8 = 1000 或者 select account where sustring(nickname,1,3) = ‘zhangxiaolong’;

4、使用!=或<>时

建议使用 <,<=,=,>,>=,between等;

5、某些or值条件可能导致全表扫描

如:select account from member where id = 1 or id = 2;
建议使用union all,改为 select account from member where id = 1 union all select account from member where id = 2;

6、强制类型转换的情况下,不会使用索引,会走全表扫描

如:你表中定义的 salary 是int,但是你sql传入字符串 select account from member where salary=‘100’ 即使salary有索引也用不到

你可能感兴趣的:(——【数据库】)