繁体   English   中英

在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/ )。

是的,我的头衔几乎说明了一切。 示例:记录:
12,詹姆斯,单簧管,鸡
16,比利,鼓,培根
15,Shane,吉他,比萨

系统将随机选择一条记录。 然后会回显“一个名叫$ firstname的男孩喜欢$ favoritefood”。

这样的事情。 救命?

关于SQL注入的标准免责声明。 这应该可以,但是我没有尝试:

// 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;
}

那这个呢 ?

select ... from tableT limit $i,1

$ i应该是介于0和tableT中的行数之间的随机数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM