画像でいっぱいのデータベースがあり、2 つのランダムな画像を吐き出して表示したいと考えています。このコードはそれを適切に実行しますが、特にデータベースに最終的に多くの行が含まれる場合は、これが最善の方法であるとは確信していません。MySQL の rand() 関数を使用して結果を 2 つに制限することを検討しましたが、大規模なデータベースでは rand() が比較的遅いことがわかりました。もう 1 つの問題は、二重データベース クエリにあります。img_id で 2 つのランダムな行を選択するより良い方法はありますか?
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'] . '" />';
}
クエリをより効率的にするための提案はありますか?