通过建立索引优化,建立索引原则:
- 最左前缀匹配原则
- =和in可以乱序
- 尽量选择区分度高的列作为索引
- 索引列不能参与计算
- 尽量的扩展索引,不要新建索引
not in/not exists都不是好习惯
bad case:
select * from order where status!=0 and stauts!=1
good case:
select * from order where status in(2,3)
非前导模糊查询可以使用索引
bad case:
select * from order where desc like '%XX'
good case:
select * from order where desc like 'XX%'
bad case:
select * from order where YEAR(date) < = '2020'
good case:
select * from order where date < = CURDATE()
bad case:
select * from user where login_name=?
good case:
select * from user where login_name=? limit 1
bad case:
select * from order where date < = CURDATE()
good case:
$curDate = date('Y-m-d');
$res = mysql_query(
'select * from order where date < = $curDate'
);