rand()函数过慢
最近在对网站做优化的过程中,发现mp对数据查询特别慢,前期还好,当数据达到万级的时候就开始慢下来了(目前11万条数据)
select * from article order by rand() limit 5
查找了资料发现,这条语句虽然简单,但它会遍历整张表,导致速度过慢,所以我的思路很简单,那就是只让他遍历部分数据,因为我是线报型网站,过早的数据对我无用,所以我只遍历最新的1000条数据,从中随机挑选5条数据
select * from article where id in (select t.* from(select id from article ORDER BY id desc limit 1000) as t) ORDER BY rand() limit 5
优化前
优化后
按时间排序获取最新数据过慢(获取24小时内热门消息)
获取最新的1000条数据(我这里每天数据在200条左右),获取当天的数据,然后对这1000条数据进行热度排序,思路和上方一样,直接上结果代码
select t.* from (select t2.* from (select * from article ORDER BY id desc limit 1000) as t2) as t where t.create_time>1664028608 ORDER BY t.visit desc limit 5