gpt4 book ai didi

php - 从sql表中选择随机行时如何防止选择已删除的ID

转载 作者:太空宇宙 更新时间:2023-11-03 11:05:29 24 4
gpt4 key购买 nike

我想通过唯一 ID 从产品数据库中选择随机行。我需要在每个页面上显示 3-4 个随机产品...

我是这样开始的

$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `products` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( " SELECT * FROM `products` WHERE id = $offset LIMIT 1" );
$n=mysql_num_rows($result);

if ($n>0){
while($row = mysql_fetch_array($result)){
$id = $row["id"];
$cod_produs = $row["cod_produs"];
$nume_produs = $row["nume_produs"];
$titlul_paginii = $row["titlul_paginii"];
$nume_intermediar = str_replace (" ", "-", $nume_produs);
$nou_nume_produs = strtolower($nume_intermediar);
$detalii = $row["detalii"];
$seo_descriere = $row["seo_descriere"];
$materiale = $row["materiale"];
$numere = $row["numere"];
$pret = $row["pret"];
$categorie = $row["categorie"];
$subcategorie = $row["subcategorie"];
$data_adaugare = strftime("%b %d, %Y", strtotime($row["data_adaugare"]));

}

echo ("The id of the product is ".$id." and his name is ".$nume_produs);

};
?>

问题是我的代码返回了我随时间删除的 ID...我如何防止这样做?

我如何才能一次返回 3 或 4 个唯一 ID,并且愿意接受更好的方法?

最佳答案

通常的做法是:

SELECT * FROM `table` ORDER BY RAND() LIMIT 0,1;

您可以在 Selecting random record from MySQL database table. 阅读解释

对于您的代码:

mysql_query( " SELECT * FROM `products` ORDER BY RAND() LIMIT 0,3" );

根据 OP 评论进行编辑

然后,您可以获得数据的子集。修改代码:

$offset_result = mysql_query( "SELECT FLOOR(MAX(id) * RAND() - 1000) AS `offset` 
FROM `products` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( " SELECT * FROM `products`
WHERE id between $offset and $offset + 1000
ORDER BY RAND()
LIMIT 0,3" );

快速的解决方案是获得 3 个随机 ID:

$randoms_id = '-1';
for($i=0;$i<3;$i++) {

$id_result = mysql_query( " SELECT id FROM `products`
WHERE id >=
(SELECT FLOOR( MAX(id) * RAND())
FROM `products` )
ORDER BY id LIMIT 1;");
$id_row = mysql_fetch_object( $id_result );
$id = $id_row->id;

$randoms_id = $randoms_id . ',' . $id;
}
$result = mysql_query( " SELECT * FROM `products`
WHERE id in ($randoms_id);")

关于php - 从sql表中选择随机行时如何防止选择已删除的ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12159512/

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