开发者

How to stop looking in a database after X rows are found?

开发者 https://www.devze.com 2022-12-25 08:34 出处:网络
I have a query开发者_JAVA技巧 to a database that returns a number X of results. I am looking to return a maximum of 10 results. Is there a way to do this without using LIMIT 0,9? I\'ll use LIMIT if I

I have a query开发者_JAVA技巧 to a database that returns a number X of results. I am looking to return a maximum of 10 results. Is there a way to do this without using LIMIT 0,9? I'll use LIMIT if I have to, but I'd rather use something else that will literally stop the searching, rather than look at all rows and then only return the top 10.


If you're not doing any ordering in the query, then "LIMIT 10" will stop after the first 10 matching rows. But as soon as you do ordering, then all the rows will have to be processed, sorted, and THEN the first 10 rows will be returned.

Think of it as the difference between "ok, first 10 people in line can come in", and "ok, the 10 tallest people in line can come in". First one you just open the door and let in 10 people. Second one you have to through the whole line to find the 10 tallest people.


The LIMIT syntax is the most reliable means of returning a specified number of rows. For ten rows, use:

LIMIT 10

Using LIMIT 0, 9 will return 9 rows, not 10. And there's no benefit to specifying the offset if you're going to start at zero anyways.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号