当前位置:Gxlcms > 数据库问题 > Mysql写出高质量的sql语句的几点建议

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

时间:2021-07-01 10:21:17 帮助过:22人阅读


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 a
left join table_b b
	on a.id = b.id
left join table_c c
	on a.id = c.id
where a.id > 100
	and b.id < 200

优化后:
select
	*
from (
	select	
		*
	from table_a
	where id > 100
) a
left join(
	select	
		*
	from table_b
	where id < 200
)b
	on a.id = b.id
left join table_c
	on 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。






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

标签:mysql写出高质量的sql语句的几点建   高质量的sql语句   

人气教程排行