首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在MySQL数据库中随机选择两行

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

Stack Overflow用户
提问于 2012-12-19 02:42:25
回答 5查看 3.6K关注 0票数 5

我有一个充满图像的数据库,我想输出并显示两个随机的图像。这段代码做得很好,但我不认为这是最好的方法,特别是当数据库最终会有很多行的时候。我曾研究过使用MySQL的rand()函数并将其限制为两个结果,但从我所了解的情况来看,rand()在大型数据库上相对较慢。另一个问题是双数据库查询。有没有更好的方法通过img_id选择两个随机的行?

img_id是auto_incremented行,但不能假定它是连续的。

代码语言:javascript
复制
//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'] . '" />';
}

有什么建议可以让查询更高效吗?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2012-12-19 02:45:05

你可以使用

代码语言:javascript
复制
SELECT img_id, title, file_loc FROM images order by rand() limit 2

所以你最终会得到

代码语言:javascript
复制
$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?

票数 6
EN

Stack Overflow用户

发布于 2012-12-19 02:48:51

使用每隔x(您的调用)执行一次的脚本来标记要显示的两张图片。

票数 0
EN

Stack Overflow用户

发布于 2012-12-19 02:49:13

对于MySQL,我不太确定,在MS SQL中,我会这样做:

代码语言:javascript
复制
SELECT TOP 2 img_id, newid() FROM images ORDER BY newid()

如果它在MySQL中类似地工作,那么它将是

代码语言:javascript
复制
SELECT img_id, uuid() FROM images ORDER BY uuid() LIMIT 2
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13939385

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档