0

I have query that gets 10 random posts , and as you know this is very slow and heavy query, is there any alternatives to submit this query without any slow appearance?

my current rand query :

SELECT * FROM posts ORDER BY RAND() LIMIT 10
fredley
  • 32,953
  • 42
  • 145
  • 236
homerun
  • 19,837
  • 15
  • 45
  • 70

1 Answers1

0

From MySQL document:

SELECT * FROM tablename ORDER BY RAND() LIMIT 1

works for small tables, but once the tables grow larger than 300,000 records or so this will be very slow because MySQL will have to process ALL the entries from the table, order them randomly and then return the first row of the ordered result, and this sorting takes long time. Instead you can do it like this (atleast if you have an auto_increment PK):

SELECT MIN(id), MAX(id) FROM tablename;

Fetch the result into $a

//php code

$id=rand($a[0],$a[1]);

SELECT * FROM tablename WHERE id>='$id' LIMIT 1

Joel
  • 111
  • 7