What is the fastest way of selecting 2 columns from the same (random) record in MySQL?
I wa开发者_开发技巧nt I retrieve a pair of columns from the same record, in a random basis. I've heard that Rand is very inefficient, however, so I'd like to use a different way. (Lots of articles claims so, including http://akinas.com/pages/en/blog/mysql_random_row/).
So yeah, my title pretty much says it all. Example: Records:
12, James, Clarinet, Chicken 16, Billy, Drums, Bacon 15, Shane, Guitar, PizzaThe system would randomly pick a record. It'll then echo 'A boy named $firstname likes $favoritefood'.
Something like that. Help?
Standard disclaimer about SQL injection. This should work, but I didn't try it:
// Get the number of rows in the table
$count = mysql_fetch_assoc(mysql_query('SELECT COUNT(`id`) AS `count` FROM `table`'));
// Use those to generate a random number
$rand = rand(1,$count['count']);
// Select the two columns we need, and use limit to set the boundaries
$query = 'SELECT `firstName`, `favoriteFood` FROM `table` LIMIT '.$rand.',1';
// Run the query
if(($result = mysql_query($query)) !== FALSE) {
// Dump the result into two variables
list($firstname, $favoritefood) = mysql_fetch_assoc($result);
// Echo out the result
echo 'A boy named '.$firstname.' likes '.$favoritefood;
}
what about this ?
select ... from tableT limit $i,1
$i should be random number between 0 and number of rows in tableT
精彩评论