PDA

View Full Version : Random Query Replacement Question


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?

vbresults
04-03-2011, 08:48 PM
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?

Both queries are only returning one result for me in phpMyAdmin; are you using `vB_Database::query_read`?

Boofo
04-03-2011, 10:48 PM
I was using that query in the Run SQL Query area in the Admin CP. You are right, though, that is only returns one result when it is is set as $db->query_read. I would still think the LIMIT 1 should work in the Run SQL Query, though, shouldn't it?