Mysql写出高质量的sql语句的几点建议

来源:互联网 发布:怎么禁止程序访问网络 编辑:程序博客网 时间:2024/06/05 13:26


        CleverCode在实际的工作也写过一些低效率的sql语句。这些语句会给数据库带来很大的压力,最主要的表现就是sql语句运行慢,后来逐渐的去优化和尝试。总结了一些高质量的sql语句的写法。这里CleverCode总结一下分享给大家。

         【 CleverCode发表在csdn博客中的原创作品,请勿转载,原创地址:http://blog.csdn.net/clevercode/article/details/46341147


1 建议一:尽量避免在列上运算

      尽量避免在列上运算,这样会导致索引失效。

1.1 日期运算

优化前:
select * from system_user where date(createtime) >= '2015-06-01'
优化后:
select * from system_user where createtime >= '2015-06-01'

1.2 加,减,乘,除

优化前:
select * from system_user where age + 10 >= 20
优化后:
select * from system_user where age >= 10

2 建议二:用整型设计索引

       用整型设计的索引,占用的字节少,相对与字符串索引要快的多。特别是创建主键索引和唯一索引的时候。
1)设计日期时候,建议用int取代char(8)。例如整型:20150603。
2)设计IP时候可以用bigint把IP转化为长整型存储。


3 建议三:join时,使用小结果集驱动大结果集

      使用join的时候,应该尽量让小结果集驱动大的结果集,把复杂的join查询拆分成多个query。因为join多个表的时候,可能会有表的锁定和阻塞。如果大结果集非常大,而且被锁了,那么这个语句会一直等待。这个也是新手常犯的一个错误!
优化前:
select*from table_a aleft join table_b bon a.id = b.idleft join table_c con a.id = c.idwhere a.id > 100and b.id < 200

优化后:
select*from (select*from table_awhere id > 100) aleft join(select*from table_bwhere id < 200)bon a.id = b.idleft join table_con a.id = c.id

4 建议四:仅列出需要查询的字段

仅列出需要查询的字段,新手一般都查询的时候都是*,其实这样不好。这对速度不会有明显的影响,主要考虑的是节省内存。
优化前:
select * from system_user where age > 10
优化后:
select username,email from system_user where age > 10

5 建议五:使用批量插入节省交互

优化前:
insert into system_user(username,passwd) values('test1','123456')insert into system_user(username,passwd) values('test2','123456')insert into system_user(username,passwd) values('test3','123456')

优化后:
insert into system_user(username,passwd) values('test1','123456'),('test2','123456'),('test3','123456')

6 建议六:多习惯使用explain分析sql语句




7 建议七:多使用profiling分析sql语句时间开销

     profiling的使用请查看我另外一篇博客,《Mysql使用profiling分析慢sql语句的原因》:http://blog.csdn.net/clevercode/article/details/46310835。


版权声明:

1)原创作品,出自"CleverCode的博客",请勿转载,否则追究版权法律责任。
2)原创地址:http://blog.csdn.net/clevercode/article/details/46341147。
3)分类地址(Mysql数据库总结):http://blog.csdn.net/clevercode/article/category/3262205(博客持续增加,关注请收藏)
4)欢迎大家关注我博客更多的精彩内容:http://blog.csdn.net/CleverCode。






2 1
原创粉丝点击