MySQL RAND() 不工作,总是得到相同的结果 [英] MySQL RAND() not working, always getting same result
问题描述
我有这个 MySQL 查询:
I have this MySQL query :
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;
}
}
我想每次执行都得到一个新场景,但我总是得到相同的场景.这是什么问题?有人可以给我指点我必须搜索的方向吗?
I want to get everytime a new scene for each execution, but I always get the same scene. Whats the issue? Can someone make me a few pointers in which direction I have to search ?
推荐答案
您需要做的是将随机种子绑定到每一行,并且每次都绑定一个新种子.为此,请为您的表分配一个随机值作为别名临时列,然后然后从中选择.
What you need to do is tie a random seed to each row, and tie a new one each time. Do this by assigning a random value as an aliased transient column to your table, and then select from it.
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 看起来像这样:
Using PDO it's going to look something like this:
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";
}
}
我不确定你想用其余代码完成什么,但它大多看起来很笨拙.
I'm not sure what you were trying to accomplish with the rest of your code, but it mostly looks like cruft.
这篇关于MySQL RAND() 不工作,总是得到相同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!