Get random value mysql

0

I would like to know some way to get some random value from MySQL without repeating, I am using this line:

$query = mysql_query("SELECT * FROM users ORDER BY RAND()");

    
asked by anonymous 28.10.2015 / 21:10

2 answers

2

The RAND () method of MYSQL supports SEED that forces it to generate a different random number for each SEED which will cause it to have a different order for each of them, but the same order for a same SEED.

You can use the seconds of the day for a SEED setting.

$sql = sprintf("SELECT * FROM users ORDER BY RAND(%d)", time()%(24*60*60) );
$query = mysql_query($sql);

To use minutes use time ()% (24 * 60)

This code will cause the order to always be repeated at the same time of day.

How does this help? Well, it's easier, for example, to randomly show someone a list and keep that list for as long as you want. Assuming that for each user you want to show a different random list, but you want the list to be the same while the user is logged in. You can use the id of this user along with some information that always changes as the number of the day for the seed and thus during any period will have an identical random list every time you run the query, avoiding having to code it in the language. p>     

28.10.2015 / 21:44
1

You can try to catch all users at once.

SELECT DISTINCT * FROM users LIMIT X ORDER BY RAND()

Where X is the number of users

    
28.10.2015 / 21:22