php - 从 MySQL 中的相同(随机)记录中选择 2 列的最快方法是什么?

标签 php mysql sql

我想从同一记录中随机检索一对列。然而,我听说 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/

相关文章:

php - 适用于 PHP 7 的 Docker gd 模块

php - Raspberry php不向arduino发送串行数据

javascript - Markdown 美化

php exec 没有按预期工作

MySQL 转置

SQL Server 2000 删除顶部 (1000)

mysql - 查看对表执行的约束 - SQL

mysql - 多个连接的奇怪 SQL 问题

php - jTable jQuery 插件 为什么我的 MySQL 存储过程失败?

sql - 从 PostgreSQL 中选择日期(时间戳)作为字符串(字符),注意 NULL 值