2014-10-17 49 views
0

我有一列有4行。我使用查詢返回一個隨機行,但95%的時間,我得到表中的第一行。我很少得到比第一排更多的其他排。 在PHP中使用這個函數的方式有問題嗎?只有不能從我的SQL的PHP​​ RAND()查詢接收隨機結果

//Array with the data to insert 
$sql_array = array(
    'rightcolumn' => 'rightcolumn', 
); 

// Create the SQL statement 
$sql = 'SELECT * FROM ' . rightcolumn . ' 
     ORDER BY RAND() = ' . 1; 

// Run the query 
$result = $db->sql_query($sql); 

// $row should hold the data you selected 
$row = $db->sql_fetchrow($result); 

// Be sure to free the result after a SELECT query       
$db->sql_freeresult($result); 

// Show we got the result we were looking for 
echo $row['rightcolumn']; 

回答

1

ORDER BY RAND(),除去=1

ORDER BY RAND是非常低效有一張大桌子,4行不過是罰款

+0

或改變'LIMIT 1'。 – 2014-10-17 01:56:36

+0

以及那可能是'= 1'的想法來自哪裏,所以你會同時使用'ORDER BY RAND()LIMIT 1' – 2014-10-17 01:57:59

+0

謝謝,解決了它! – starshine 2014-10-17 02:01:56

0

牢記RAND()返回值[0, 1)範圍 - 在RAND() = 1表達總是返回false。

所以你的ORDER BY子句可以表示爲ORDER BY false,這沒什麼意義。

相反,你必須通過一個隨機值順序,即:

ORDER BY RAND() 
+0

謝謝!我很欣賞這個解釋,幫助我理解它。會放棄投票,但我是一個新用戶,顯然我不能。 – starshine 2014-10-17 02:03:10

0

我接着上面zerkms和袞的說明。

的說法應該是:

$sql = 'SELECT * FROM ' . rightcolumn . ' 
     ORDER BY RAND()';