在MySQL数据库中选择两个随机行

Hat*_*Hat 5 php mysql

我有一个充满图像的数据库,我想吐出并显示两个随机图像.这段代码做得很好,但我不相信这是最好的方法,特别是如果数据库最终会有很多行.我已经研究过使用MySQL的rand()函数并将其限制为两个结果,但是从我读过的内容来看,rand()在大型数据库上相对较慢.另一个问题是在双数据库查询中.是否有更好的方法可以通过img_id选择两个随机行?

img_id是一个auto_incremented行,但不能假设是连续的.

//get all image ids
$query = $conn->prepare('SELECT img_id FROM images');
$query->execute();
$result = $query->fetchAll();

//create an array in which to put all the ids
$list_imgs = array();

//put the ids into the array to search over
for ($x=0; $x < count($result); $x++) {
    array_push($list_imgs, $result[$x]['img_id']);
}

//output two random images
for ($x=0; $x < 2; $x++) {
    //create random index for search
    $rand = array_rand($list_imgs);

    //query to select one image
    $query = $conn->prepare('SELECT title, file_loc FROM images WHERE img_id=?');
    //random index value in array of img_ids
    $query->execute(array($list_imgs[$rand]));
    $result = $query->fetchAll();

    echo 'title:' . $result[0]['file_loc'] . '<br /><img src="' . $result[0]['file_loc'] . '" />';
}
Run Code Online (Sandbox Code Playgroud)

任何提高查询效率的建议?

Div*_*com 5

你可以用

SELECT img_id, title, file_loc FROM images order by rand() limit 2
Run Code Online (Sandbox Code Playgroud)

所以你最终得到了

$query = $conn->prepare('SELECT img_id, title, file_loc FROM images order by rand() limit 2');
$query->execute();
$result = $query->fetchAll();

foreach($result as $row) {
    echo 'title:' . $row['file_loc'] . '<br /><img src="' . $row['file_loc'] . '" />';
}
Run Code Online (Sandbox Code Playgroud)

请注意,rand()的顺序在大型表上可能特别慢.请参阅如何优化MySQL的ORDER BY RAND()函数? 如何优化它