由rand PHP编写的Mysql命令


Mysql order by rand PHP

我正在使用

$nameimg = mysql_query("SELECT * 
                        FROM images 
                        WHERE id='".$row['imgID']."' 
                        ORDER BY RAND()    
                        LIMIT 10");

显示所述用户的随机图像,但不显示随机图像。它只是通过提交的时间显示。

WHERE条件检查ID通常会将结果集减少到一行,因此整个ORDER BY子句变得无用。

您应该考虑一下您的模式并重新设计查询。

您应该使用PHP来随机打乱数组。如果您感兴趣的字段名为url:

$req = mysql_query("SELECT url FROM images WHERE user_id = '{$row['userID']}'");
$images = array();
while($image = mysql_fetch_array($req)) {
    $images[] = $image['url'];
}
shuffle($images);
$tenImages = array_slice($images, 0, 10);

编辑请考虑在准备好的报表中使用PDO。

更新为什么不一次选取十张图像?

$images = array();
while(count($images) < 10) {
    $req = mysql_query("SELECT url FROM images WHERE user_id = '{$row['userID']}' LIMIT " . rand(1, 10000) . ", 1");
    $image = mysql_result($req, 0, 0);
    if(!in_array($image)) {
        $images[] = $image;
    }
}

更有趣(更快)的方式此处提供。

$ids = array();
for($i = 0 ; $i < 1000 ; $i++) {
    $ids[] = rand(1, 10000);
}
$req = mysql_query("SELECT url FROM images WHERE user_id = '{$row['userID']}' AND id IN (" . implode(',', $ids) . ") LIMIT 10");