php mysql order by id desc优化

今天来讲一个mysql order by id desc的性能问题,原始表:news,数据14W. 之前文章数量比较少, 在加了指定mysql索引后速度很快,基本上是秒开,一直没有发现这个问题,但是随着数据的增加,我的了一个侧边栏显示很慢,功能是提取最新20条数据。之前的sql: select * from news where category_id = 2 and province_id = 2 limit 20; 但是我没有加order by id 排序,所以数据出来的是按数据库递增出来的,如果对于一个新闻列表来说明显是不对的,我们应该提取最新的数据显示出来。于是我加上了order by id desc,但是加上之后我发现一个奇怪的问题,select * from news where category_id = 2 order by id desc limit 20很快,但是select * from news where category_id = 2 and province_id = 2 order by id desc limit 20就很慢,改成order by id asc也很快。 其实这是因为:

MySQL的limit工作原理就是先读取n条记录,然后抛弃前n条,读m条想要的,所以n越大,性能会越差。这里需要注意的是如果我们只查询id,速度不会受到影响的。

如: select id from news where category_id = 2 and province_id = 2 order by id desc limit 20,你可以尝试一下。 下面给出解决方案:

  1. select * from news inner join (select id from news where category_id = 2 and province_id = 2 order by id desc limit 20) as id using(id); 秒开。(原理,快速查询出来满足条件胡id然后关联查询)
  2. 添加搜索和order by id的联合索引,并且强制使用这个索引,例如:(category_id, province_id,id)的联合索引为idx_1,sql: select * from news force index(idx_1) where category_id = 2 and province_id = 2 order by id desc limit 20; 秒开 ,为什么要加强制使用,因为有时候索引多了它不知道用哪一个,我测试过加了索引后一样很慢,但是强制使用就变快了。

有时候遇见问题多上网搜索一下,不过我的建议是最好不要用baidu,当然简单的问题百度还是有,但是建议多用用bing和google。

Be the First to comment.

猜你喜欢

转载自blog.csdn.net/wccczxm/article/details/89265999