SQL技巧Tips

来源:互联网 发布:企业大数据架构 编辑:程序博客网 时间:2024/06/04 00:24

一、一些常见的SQL实践

(1) 负向条件查询不能使用使用索引

select * from order where status!=0 and stauts !=1 
not in / not exists 都不是好习惯

可以优化为in查询:

select * from order where stauts in(2,3)

(2)前导模糊查询不能使用索引

select * from order where desc like '%XX'
而非前导模糊糊查询则可以
select * from order where desc like 'XX%'

(3)数据区分不大的字段不宜使用索引

select *from user where sex =1
原因:性别只有男女,每次过滤掉的数据太少,不宜用于索引

经验上,能过滤80%数据的时候就可以使用索引。对于订单状态,如果状态很少,不宜使用索引,如果状态值很多,能够过滤大量数据,则应该建立索引。

(4)在属性上进行计算不能命中索引

select * from order where YEAR(date)<='2017'
即使date建立了索引,也会全表扫描,可以优化为值计算:

select * from order where date<=CURDATE()
或者
select * from order where date <='2017-01-01'

二、并非周知的SQL实践

(5)如果业务大部分是单挑查询,使用Hash索引性能更高,例如用户中心

select * from user where uid = ?
select * from user where login_name=?
原因:

B-Tree索引的时间复杂度是O(log(n))

Hash索引的时间复杂度是O(1)

(6)允许为null的列,查询有潜在大坑

单列索引不存在null值,复合索引不存在全为null的值,如果列允许为null,可能会得到“不符合预期的”结果集

select *from user where name !='tommy'
如果name允许为null,索引不存储null值,结果集中不会包含这些记录。

所以,请使用not null约束以及默认值

(7)复合索引最左前缀,并不是值SQL语句的where顺序要和复合索引一致

用户中心建立了(name ,password)的复合索引

select * from user where name =? and password=?
select * from user where password =? and name = ?
都能命中索引
select * from user where name =?

也能命中索引,满足复合索引最左前缀

select * from user where password = ? 
不能命中索引,不满足复合索引最左前缀

(8)使用ENUM而不是字符串

ENUM保存的是TINYNIT,别在枚举中加字符串,字符串空间大,效率低

三、小众但有用的SQL实践

(9)如果明确知道只有一条结果返回,limit 1能够提高效率

select * from user where name=?

可以优化为

select * from user where name=? limit 1

(10)把计算放到业务层而不是数据库层,除了节省数据的cpu,还有意想不到的查询缓存优化效果。

select * from order where date<= CURDATE()
应该优化为

$curDate = date('Y-m-d');$res = mysql_query('select * from order where date<=$curDate');

原因:

释放了数据库的CPU

多次调用,传入的SQL相同,才可以利用查询缓存

(11)强制类型转换会全表扫描

select * from user where phone = 13500000001
这句没法命中phone索引,需要改为

select * from user where phone = '13500000001'

注:末了,再加一条,不要使用select *,只返回需要的列,能够大大的节省数据传输量,与数据库的内存使用量。

原创粉丝点击