2012-06-29 80 views
0

我有一個示例代碼在php中使用隨機的mysql不能隨機的ID?

products(id, name) 
1 | Apple 
2 | Sony 
3 | Nokia 
4 | Samsung 
5 | LG 
6 | Motorola 
7 | Ekricson 

和MySQL:

SELECT id, name FROM `products` AS prod 
ORDER BY RAND(prod.id) LIMIT 5 

,當我運行代碼的結果是:

4 | ... 
7 | ... 
1 | ... 
5 | ... 
6 | ... 

但下次......是的結果是:

4 | ... 
7 | ... 
1 | ... 
5 | ... 
6 | ... 

Id隨機運行時不會改變,如何修復ix

+0

嘗試從RAND取出prod.id()的參數是被用來生成數字的_repeatable_序列的種子值。 (根據文件) – NickSlash

回答

1

RAND(x)函數中的參數是種子,所以您每次都使用相同的值播種它。相反,將其保留爲RAND(),它會有所不同。

7

您應該使用ORDER BY RAND(),而不是ORDER BY RAND(prod.product_id)

RAND manual

RAND(), RAND(N) 

Returns a random floating-point value v in the range 0 <= v < 1.0. 
If a constant integer argument N is specified, it is used as the seed value 
which produces a repeatable sequence of column values. 
0

SELECT ID,名字從products AS督促 ORDER BY RAND() LIMIT 5

0

使用這種方式:

SELECT id, name FROM `products` AS prod 
ORDER BY RAND() LIMIT 5; 

參見手冊here