简体   繁体   English

mysql命令由rand PHP

[英]Mysql order by rand PHP

I am using 我在用

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

To show random images by said user, but it's not showing random images. 由所述用户显示随机图像,但不显示随机图像。 It's just showing via time submitted. 它只是通过提交的时间显示。

WHERE conditions checking for an ID usually reduce the result set to one row, so the whole ORDER BY clause becomes useless. WHERE条件的ID检查通常减少的结果设置为一列,所以整个ORDER BY子句变得无用。

You should think about your schema and redesign the query. 您应该考虑自己的架构并重新设计查询。

You should rather use PHP to randomly shuffle the array. 您应该使用PHP随机地对数组进行随机排列。 If the field you are interested in is called url : 如果您感兴趣的字段称为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);

Edit. 编辑。 And please consider using PDO for prepared statements . 并且请考虑将PDO用于准备好的语句

Update. 更新。 Why not picking the ten images one at a time? 为什么不一次选择十张图像?

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

Funnier (and faster) way. 更有趣(更快)的方式。 Provided here . 在这里提供。

$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");

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

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