How does select * from table rand() work?
I have a simple question.
When I execute "Select * from table where rand()", I get rand # of rows. Is this same as select * from table limit rand() (it does not开发者_Python百科 work though) ?
A where
clause in a database query is simply a statement that results in a true or false value as each row in the table is being considered for inclusion in the result set. Generally that T/F calculation involves one or more fields from the table being queried, but it's not a requirement.
When you do ... WHERE rand()
, you're basically getting a random value in the range 0 <= N < 1
for each row. MySQL casts that to a boolean by rounding the value to 0 or 1. So a random number 0.5->0.999 becomes 1 (TRUE) and a random number 0 -> 0.49999 rounds to 0 (FALSE).
Limit
the results of your MySQL query to results between a certain number range. while Select * from table where rand()
search the whole table and select a random
When you use
... LIMIT RAND()
You need to consider what the RAND() function does - it returns a value between 0.0 and 1.0 - so it's effectively LIMIT(0) - you'll always have zero return results.
http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_rand
rand()
always evaluates to a number between 0 and 1.
If you use it in a limit clause, it will return no rows, because it evaluates to less than 1 row.
If you use it in the where clause, it should always evaluate to true, as it is always greater than 1, and will return all rows, not a random number of rows.
精彩评论