Boofo
04-03-2011, 02:36 AM
I'm trying to do a random query to pull a random user out of the user table. I want to stay away from the ORDER BY RAND query, if at all possible, as it can be slow on larger tables. Here are the two queries I have come up with so far:
SELECT userid, username FROM user T JOIN (SELECT FLOOR(MAX(userid)*RAND()) AS ID FROM user) AS x ON T.userid >= x.ID LIMIT 1
SELECT userid, username FROM user T JOIN (SELECT MAX(userid) AS ID FROM user) AS x ON T.userid >= FLOOR(x.ID*RAND()) LIMIT 1;
They both seem to run fairly fast but they pull more than one user out of the table. Can anyone tell me where I am screwing up on the LIMIT 1 and which query is actually better than the other for large tables?
SELECT userid, username FROM user T JOIN (SELECT FLOOR(MAX(userid)*RAND()) AS ID FROM user) AS x ON T.userid >= x.ID LIMIT 1
SELECT userid, username FROM user T JOIN (SELECT MAX(userid) AS ID FROM user) AS x ON T.userid >= FLOOR(x.ID*RAND()) LIMIT 1;
They both seem to run fairly fast but they pull more than one user out of the table. Can anyone tell me where I am screwing up on the LIMIT 1 and which query is actually better than the other for large tables?