# sql好的书写习惯 1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引。 2.应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如:select id from t where num is null可以在num上设置默认值0,确保表中num列没有null值,然后这样查询:select id from t where num=0 3.应尽量避免在 where 子句中使用!=或<>操作符,否则引擎将放弃使用索引而进行全表扫描。 4.应尽量避免在 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 5.in和 not in 也要慎用,否则会导致全表扫描,如:select id from t where num in(1,2,3) 对于连续的数值,能用 between 就不要用 in 了:select id from t where num between 1 and 3 6.不要在 where 子句中的“=”左边进行函数、算术运算或其他表达式运算,否则系统将可能无法正确使用索引。 7.很多时候用 exists 代替 in 是一个好的选择:select num from a where num in(select num from b)用下面的语句替换:select num from a where exists(select 1 from b where num=a.num) 8.尽量使用数字型字段,若只含数值信息的字段尽量不要设计为字符型,这会降低查询和连接的性能,并会增加存储开销。这是因为引擎在处理查询和连接时会逐个比较字符串中每一个字符,而对于数字型而言只需要比较一次就够了。 9.尽可能的使用 varchar/nvarchar 代替 char/nchar 10.任何地方都不要使用 select \* from t ,用具体的字段列表代替“\*”,不要返回用不到的任何字段。 11.尽量避免使用游标,因为游标的效率较差,如果游标操作的数据超过1万行,那么就应该考虑改写。 12.尽量避免大事务操作,提高系统并发能力。 13.尽量避免向客户端返回大数据量,若数据量过大,应该考虑相应需求是否合理。 ### **优化的宗旨是尽量避免全表扫描** 加缓存,memcached,redis; 还是慢,就做主从复制或主主复制,读写分离,mysql自带分区表 [https://www.kancloud.cn/thinkphp/mysql-optimization-reference/36109](https://www.kancloud.cn/thinkphp/mysql-optimization-reference/36109) [https://www.kancloud.cn/thinkphp/mysql-design-optimalize/39319](https://www.kancloud.cn/thinkphp/mysql-design-optimalize/39319) SQLAdvisor 是由美团点评北京DBA团队开发维护的 SQL 优化工具:输入SQL,输出索引优化建议。 GitHub 地址:[https://github.com/Meituan-Dianping/SQLAdvisor](https://github.com/Meituan-Dianping/SQLAdvisor)