# mysql 优化 架构师必备 **Repository Path**: pullwind/mysqlUpreme ## Basic Information - **Project Name**: mysql 优化 架构师必备 - **Description**: 架构师必要的mysql知识 - **Primary Language**: Unknown - **License**: AGPL-3.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 1 - **Created**: 2023-06-14 - **Last Updated**: 2023-06-14 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # mysql 基本的习惯常识 ## 应尽量避免在where子句中使用or来连接条件,否则将导致引擎放弃使用索引而进行全表扫描,如: select id from t where num=10 or num=20可以这样查询: select id from t where num=10 union all select id from t where num=20 ## 慎用in和not in 逻辑 in 和not in也要慎用,否则会导致全表扫描,如:| select id from t1 where nuth in (select id from t2 where id>10) 此时外层查询会全表扫描,不使用索引。可以修改为: select id from t1,(select id from t1 where id>10)t2 where t1.id=t2.id此时索引被使用,可以明显提升查询效率。 ## 注意模糊查询 下面的查询也将导致全表扫描: select id from t where name like'%abc%" 模糊查询如果是必要条件时,可以使用select id from t where name like'abc%来实现模糊查询,此时索引将被使用。如果头匹配是必要逻辑,建议使用全文搜索引擎(Elastic search、Lucene、Solr等)。 ## 避免查询条件中字段计算 应尽量避免在where子句中对字段进行表达式操作,这将导致引擎放弃使用索引而进行全表扫描。如: select id from t where num/2=100应改为: select id from t where num=100*2 ## 字段设定 字符和数值 尽量使用数字型字段,若只含数值信息的字段尽量不要设计为字符型,这会降低查询和连接的性能,并会增加存储开销。这是因为引擎在处理查询和连接时会逐个比较字符串中每一个字符,而对于数字型而言只需要比较一次就够了。 尽可能的使用varchar代替char,因为首先可变长度字段存储空间小,可以节省存储空间,其次对于查询来说,在一个相对较小的字段内搜索效率显然要高些。 ## 使用 exists代替in 请忘掉 in ## 避免全表扫描 对查询进行优化,应尽量避免全表扫描,首先应考虑在where及order by涉及的列上建立索引。 ## 避免判断null值 应尽量避免在where子句中对字段进行null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如: select id from t where num is null可以在um上设置默认值0,确保表中aum列没有null值,然后这样查询: select id from t where num=0 ## 避免不等值判断 应尽量避免在where子句中使用!=或>操作符,否则引擎将放弃使用索引而进行全表扫描。 #