我有这个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;
}
}
我想每次执行时都获得一个新场景,但是我总是得到相同的场景。有什么问题?有人可以给我一些指向我必须寻找的方向的指示吗?
最佳答案
您需要做的是将随机种子绑定到每一行,然后每次绑定一个新种子。为此,可以为表分配一个随机值作为别名瞬态列,然后从中进行选择。
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/