日期:2014-05-16  浏览次数:20648 次

MySql语句效率问题
people 表有id 和 name,id是主键,自动增加。
我想从id最后一个往前只搜索 n 行(n<count(*)),并找到满足条件的,如果 n行里没有找到就不继续往下找。

本来想用:select * from people where name="xxx" order by id desc limit 1000;
可我发现 limit 1000并不是只搜索1000行,而是显示满足条件的1000行。

如果写成 select * from people where id>((select count(id))-1000) order by id desc limit 1;这样效率肯定很低。

那么我就改成 select * from people where id > ((select id from people order by id desc limit 1)-1000) order by id 
desc limit 1;
请问这样效率如何?有更好方法否?

------解决方案--------------------
select *
from tb
where id>(select max(id)-1000 from tb)
limit n;
------解决方案--------------------
select * from people a inner join 

(select id from people order by id desc limit 1)-1000) b 
on a.id>b.id 
 order by a.id desc limit 1;