I’d like to optimize my queries so I look into mysql-slow.log.
Most of my slow queries contains ORDER BY RAND(). I cannot find a real solution to resolve this problem. Theres is a possible solution at MySQLPerformanceBlog but I don’t think this is enough. On poorly optimized (or frequently updated, user managed) tables it doesn’t work or I need to run two or more queries before I can select my PHP-generated random row.
Is there any solution for this issue?
A dummy example:
SELECT accomodation.ac_id,
accomodation.ac_status,
accomodation.ac_name,
accomodation.ac_status,
accomodation.ac_images
FROM accomodation, accomodation_category
WHERE accomodation.ac_status != 'draft'
AND accomodation.ac_category = accomodation_category.acat_id
AND accomodation_category.acat_slug != 'vendeglatohely'
AND ac_images != 'b:0;'
ORDER BY
RAND()
LIMIT 1
Try this:
This is especially efficient on
MyISAM(since theCOUNT(*)is instant), but even inInnoDBit’s10times more efficient thanORDER BY RAND().The main idea here is that we don’t sort, but instead keep two variables and calculate the
running probabilityof a row to be selected on the current step.See this article in my blog for more detail:
Update:
If you need to select but a single random record, try this:
This assumes your
ac_id‘s are distributed more or less evenly.