gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:05:26 24 4
gpt4 key购买 nike

我有一个充满图像的数据库,我想吐出并显示两个随机图像。这段代码做得很好,但我不相信这是最好的方法,特别是如果数据库最终会有很多行。我研究过使用 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'] . '" />';
}

有什么提高查询效率的建议吗?

最佳答案

你可以用

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'] . '" />';
}

请注意,在大型表上,通过 rand() 排序的速度可能特别慢。参见 How can i optimize MySQL's ORDER BY RAND() function?优化它的方法

关于php - 在 MySQL 数据库中选择两个随机行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13939385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com