在MySQL中从相同(随机)记录中选择2列的最快方法是什么? [英] What is the fastest way of selecting 2 columns from the same (random) record in MySQL?
问题描述
我希望我从同一条记录中随机检索一对列.我听说兰德的效率很低,所以我想用另一种方式. (很多文章都这样认为,包括 http://akinas.com/pages/en/blog/mysql_random_row/).
I want 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/).
是的,我的标题几乎说明了一切.
例子:
记录:
12,詹姆斯,单簧管,鸡肉
16,比利,鼓,培根
15,Shane,吉他,比萨饼
So yeah, my title pretty much says it all.
Example:
Records:
12, James, Clarinet, Chicken
16, Billy, Drums, Bacon
15, Shane, Guitar, Pizza
系统将随机选择一条记录.然后 回声一个名叫$ firstname的男孩喜欢$ favoritefood".
The system would randomly pick a record. It'll then echo 'A boy named $firstname likes $favoritefood'.
类似的东西.帮助吗?
推荐答案
有关SQL注入的标准免责声明.这应该可以,但是我没有尝试:
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;
}
这篇关于在MySQL中从相同(随机)记录中选择2列的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!