gpt4 book ai didi

php - MySQL RAND() 不工作,总是得到相同的结果

转载 作者:行者123 更新时间:2023-11-29 06:05:55 25 4
gpt4 key购买 nike

我有这个 MySQL 查询:

while ($x <= 9) {
$data_1 = "SELECT scene FROM star WHERE star LIKE '%".$star."%' ORDER BY RAND() LIMIT 1";
$result_1 = mysql_query ($data_1) OR die("Error: $data_1 </br>".mysql_error());

while($row_1 = mysql_fetch_object($result_1)) {
$scene = $row_1->scene;
$x = $x + 1;
}
}

我想每次执行时都获得一个新场景,但我总是得到相同的场景。有什么问题吗?有人可以给我一些指示,我必须朝哪个方向搜索吗?

最佳答案

您需要做的是将随机种子绑定(bind)到每一行,并每次绑定(bind)一个新种子。为此,请向表分配一个随机值作为别名 transient 列,然后从中进行选择。

SELECT s.scene as scene FROM (
SELECT stars.scene as scene, RAND() as seed
FROM stars
WHERE star LIKE '%".$star."%'
ORDER BY seed
) s
LIMIT 1;

使用PDO它看起来像这样:

function getScene() {
$sql = 'SELECT s.scene as scene FROM ( SELECT stars.scene as scene, RAND() as seed FROM stars WHERE star LIKE '%:star%' ORDER BY seed ) s LIMIT 1;';
$query = $this->db->prepare($sql);//'db' is the PDO connection
$query->execute(array(':star' => "Allison Brie"));

foreach ($conn->query($sql) as $row) {
print $row['scene'] . "\t";
}
}

我不确定你想用其余的代码来完成什么,但它看起来大多很糟糕。

关于php - MySQL RAND() 不工作,总是得到相同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11514682/

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