我有一个充满图像的数据库,我想输出并显示两个随机的图像。这段代码做得很好,但我不认为这是最好的方法,特别是当数据库最终会有很多行的时候。我曾研究过使用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'] . '" />';
}有什么建议可以让查询更高效吗?
发布于 2012-12-19 02:45:05
你可以使用
SELECT img_id, title, file_loc FROM images order by rand() limit 2所以你最终会得到
$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'] . '" />';
}请注意,在大型表上,order by rand()可能会特别慢。有关优化的方法,请参阅How can i optimize MySQL's ORDER BY RAND() function?
发布于 2012-12-19 02:48:51
使用每隔x(您的调用)执行一次的脚本来标记要显示的两张图片。
发布于 2012-12-19 02:49:13
对于MySQL,我不太确定,在MS SQL中,我会这样做:
SELECT TOP 2 img_id, newid() FROM images ORDER BY newid()如果它在MySQL中类似地工作,那么它将是
SELECT img_id, uuid() FROM images ORDER BY uuid() LIMIT 2https://stackoverflow.com/questions/13939385
复制相似问题