我想从同一记录中随机检索一对列。然而,我听说 Rand 效率很低,所以我想使用不同的方式。 (很多文章都这么说,包括 http://akinas.com/pages/en/blog/mysql_random_row/ )。
是的,我的标题几乎说明了一切。
例子:
记录:
12、詹姆斯、单簧管、小鸡
16、比利、打鼓、培根
15、Shane、吉他、披萨
系统会随机选择一条记录。然后它会 echo '一个叫 $firstname 的男孩喜欢 $favoritefood'。
类似的东西。帮忙?
最佳答案
关于 SQL 注入(inject)的标准免责声明。这应该可行,但我没有尝试:
// 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;
}
关于php - 从 MySQL 中的相同(随机)记录中选择 2 列的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5521037/