1. 一些常见的SQL实践
1.1. 负向条件查询不能使用索引
#not in/not exists都不是好习惯
select * from order where status!=0 and stauts!=1
#可以优化为in查询
select * from order where status in(2,3)
1.2. 前导模糊查询不能使用索引
#前导模糊查询
select * from order where desc like '%XX'
#非前导模糊查询
select * from order where desc like 'XX%'
1.3. 数据区分度不大的字段不宜使用索引
#重复数据多
select * from user where sex=1
1.4. 在属性上进行计算不能命中索引
#不能使用索引
select * from order where YEAR(date) < = '2020'
#可优化为值计算:
select * from order where date < = CURDATE()
select * from order where date < = '2020-01-01'
2. 并非周知的SQL实践
2.1. 如果业务大部分是单条查询,使用Hash索引性能更好,例如用户中心
#sql语句
select * from user where uid=?
select * from user where login_name=?
#原因:
B-Tree索引的时间复杂度是O(log(n))
Hash索引的时间复杂度是O(1)
2.2. 允许为null的列,查询有潜在大坑
#单列索引不存null值,复合索引不存全为null的值,如果列允许为null,可能会得到“不符合预期”的结果集
-- select * from user where name != 'yhh'
-- 如果name允许为null,索引不存储null值,结果集中不会包含这些记录
--所以,请使用not null约束以及默认值
2.3. 复合索引最左前缀,并不是指SQL语句的where顺序要和复合索引一致
#用户中心建立了(login_name, passwd)的复合索引
select * from user where login_name=? and passwd=?
select * from user where passwd=? and login_name=?
select * from user where login_name=?
select * from user where passwd=?
2.4.使用ENUM而不是字符串
3. 小众但有用的SQL实践
3.1. 如果明确知道只有一条结果返回,limit 1能够提高效率
#如果明确知道只有一条结果返回,limit 1能够提高效率
select * from user where login_name=?
#可以优化成
select * from user where login_name=? limit 1
#原因
你知道只有一条结果,但数据库并不知道,明确告诉它,让它主动停止游标移动
3.2. 把计算放到业务层而不是数据库层,除了节省数据的CPU,还有意想不到的查询缓存优化效果
select * from order where date < = CURDATE()
$curDate = date('Y-m-d');
$res = mysql_query(
'select * from order where date < = $curDate'
);
释放了数据库的CPU。多次调用,传入的SQL相同,才可以利用查询缓存
3.3. 强制类型转换会全表扫描
#索引失效
select * from user where phone=13800001234
3.4. **不要使用select ***
#不要使用select *