1

Possible Duplicate:
Why does MYSQL higher LIMIT offset slow the query down?

My other thread was closed due to it being a duplicate, but the duplicate, did not help me at all so I do not see a reason for closing this one also!

I have a page and I would like to sort posts in it from top to bottom by the amount of votes each post has.

I have millions of records, and the query gets really slow. it takes few good minutes to get the results.

This is fine:

SELECT `id` FROM `table` ORDER BY `votes` LIMIT 0,20;

This will take ages:

SELECT `id` FROM `table` ORDER BY `votes` LIMIT 100000,20;

I am not even talking about setting it to 1,000,000 and more.

Any ideas on how to make this faster? I tried using the code from Why does MYSQL higher LIMIT offset slow the query down? But it does not help either. Do you guys have any suggestions on how I can achieve the same result but maybe using PHP? or some better query?

Community
  • 1
  • 1
Dekken
  • 89
  • 1
  • 7

1 Answers1

2

The problem with this query is that it first needs to find out what the top 100000 are, before it can fetch 100000-1000020.

In our case we were dealing with a gallery and pages, and we simply blocked access after x pages; thus preventing the problem altogether.

If you don't already have an index on votes, start there; but I would guess you have already done that (I hope so!). Is there some other criteria you can sort on? Can you sort descending instead? Are there other ways to reduce the number of rows from 100000 to something much lower?

If all else fails, you're gonna have to find other solutions; You might need to denormalize and pregenerate what you expect to return from that query. Maybe you need to cache all the results and have a warm-up script running.

Hoping this will help you on your way..

Evert
  • 93,428
  • 18
  • 118
  • 189