数据库SQL优化(百万级数据库优化方案)

1. 对查询进行优化

    要尽量避免全表扫描首先应考虑在 where 及 order by 涉及的列上建立索引

2. where 子句

  要尽量避免在 where 子句中对字段进行 null 值判断。(否则将导致引擎放弃使用索引而进行全表扫描)

       如:select id from t where num is null;

        最好不要给数据库留NULL,尽可能的使用NOT NULL填充数据库

        备注、描述、评论之类的可以设置为NULL,其他的,最好不要使用NULL

      可以在 num 上设置默认值0,确保表中 num 列没有 null 值,然后这样查询:

        select id from t where num = 0;

      不要以为 NULL 不需要空间,比如:char(100) 型,在字段建立时,空间就固定了, 不管是否插入值(NULL也

    包含在内),都是占用 100个字符的空间的,如果是varchar这样的变长字段, null 不占用空间。

  应尽量避免在 where 子句中使用 != 或 <> 操作符,否则将引擎放弃使用索引而进行全表扫描。

  应尽量避免在 where 子句中使用 or 来连接条件。(如果一个字段有索引,一个字段没有索引,将导致引擎放弃使用索引……)

      如:select id from t where num=10 or Name = 'admin'

      可以这样查询:

        select id from t where num = 10

        union all

        select id from t where Name = 'admin'

不断更新中……

    

原文地址:https://www.cnblogs.com/zhangchaoran/p/6946506.html