Mysql 数据库常用的 SQL 语句优化
尽量避免在列上进行运算,这样会导致索引失败。
select * from t where YEAR(t.d) >=2011
#优化成以下
select * from t where d >='2011-01-01'
使用 JOIN 时,应该用小结果集驱动大结果集。同时把复杂的 JOIN 查询拆分成多个 Query。因为 JOIN 多个表,可能导致更多的锁定和阻塞。
select * from a join b on a.id = b.id
left join c on c.time = a.date
left join d on c.pid = b.aid
left join e on e.cid = a.did
注意 LIKE 模糊查询的使用,避免使用%%
select * from t where name like '%de%'
#优化成以下
select * from t where name >= 'de' and name <= 'df'
仅列出需要查询的字段,这对速度不会有明显的影响,主要是节省内存。
select * from member
#优化成以下
select id,name from member
使用批量插入语句节省内存
insert into t(id,name) values(1,'a')
insert into t(id,name) values(2,'b')
insert into t(id,name) values(3,'c')
#优化成以下
insert into t(id,name) values(1,'a'),(2,'b'),(3,'c')
limit 的基数比较大时使用 between
between 比 limit 快,建议访问海量数据可以替换,但是比较依赖 id 的连续性,中间 id 不连续会不读取,取比较后的数据,可以 desc 后再取
select * from article as article order by id limit 10000,10
#优化成以下
select * from article as article where id between 10000 and 10010 order by id
不要使用 rand 函数获取多条数据
select * from table order by rand() limit 20;
#优化成以下
select * from 'table' as t1 join (select round(rand()*(select max(id) from 'table')-(select min(id) from 'table'))+(select min(id) from 'table')) as id )as t2 where t1.id >= t2.id order by t1.id limit 1;
避免使用 null
在定义字段的时候尽量不要运行字段未 null
不要使用 count() ,而应该使用 count(*)
select id, count(*) from table;
不要做无谓的排序操作,而应该可能在索引中完成排序
select * from table order by id;