Reputation: 11
I have a rather inefficient MySQL query that has been working OK until recently as the database has grown in size. I am trying to select a random record using the ORDER BY RAND() syntax, but it is extremely slow (30+ seconds) and causes issues with my PHP script. Is there a more efficient way to write this query?
SELECT * FROM accountcampaign, accounts WHERE
accountcampaign.status='ACTIVE'
AND accountcampaign.dateLocked IS NULL
AND accountcampaign.campaignID='1'
AND ( (accountcampaign.lockedIPAddress IS NULL)
OR (accountcampaign.lockedIPAddress='')
)
AND ( (accountcampaign.dateLastEntry IS NULL)
OR (DATE(accountcampaign.dateLastEntry) < DATE(NOW()))
)
ORDER BY RAND() LIMIT 1
Upvotes: 1
Views: 454
Reputation: 4439
You don't want to use ORDER BY RAND() LIMIT 1
: it will generate one random number for every row in your table.
You should try using 2 queries :
Upvotes: 4