我有这个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;
}
}
我想每次都为每次执行获得一个新场景,但我总是得到相同的场景。问题是什么?有人可以向我指出我必须搜索的方向吗?
答案 0 :(得分:3)
您需要做的是将随机种子绑定到每一行,并每次绑一个新行。通过将随机值作为别名瞬态列分配给表来执行此操作,然后 从中进行选择。
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";
}
}
我不确定你要用其余的代码完成什么,但它看起来大概是残酷的。