![]() |
Order by rand()
I have a query that looks like:
Code:
SELECT * FROM tbl_gallery WHERE fld_userid = $UserID ORDER BY RAND() LIMIT 4 |
In order to get four random rows you could do something like the following:
php Code:
Hope this helps! |
Hi, thanks for that. I'm getting an error at the line:
Code:
$idarr[] = $row(id);Quote:
|
Hi, thanks for that. I'm getting an error at the line:
Code:
$idarr[] = $row(id);Quote:
Also, I've noticed it can generate the same number more than once, how can I stop it doing this? |
Wow - I suck...
I wrote that real quickly on too little sleep... Try this... php Code:
|
I can only give you the theory of how I did it. This isn't because I don't want to share it, but it has too many dependencies. What I did was the following:
As this is selecting an ID, which should be the primary key, it is a much faster select than choosing a random line from the database. |
Thanks for the answers, I still have a few questions about how the query is actually executed.
Say I have a query that says: Quote:
|
It will check the condition(s) first, and then pick up 4 from the remaining rows, of course.
|
That is why it is cpu intensive. RAND() will execute every time the WHERE clause does which will once for every record that would be returned regardless of the LIMIT.
From what I gather/understand/whatever, RAND will assign a random number to all the rows that fit the criteria and then order the results by those numbers. The full query still needs to run even though you have the LIMIT in there, because you are ordering the results. Only the top 4 will be returned. |
| All times are GMT. The time now is 08:45 AM. |
Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0