0

我有这个 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;
   }
} 

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

4

1 回答 1

4

您需要做的是将随机种子绑定到每一行,并每次绑定一个新种子。通过将随机值作为别名瞬态列分配给您的表来执行此操作,然后从中进行选择。

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";
    }
}

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

于 2012-07-17T00:58:28.133 回答