0

我有一个示例代码

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

4

5 回答 5

7

你应该使用ORDER BY RAND()而不是ORDER BY RAND(prod.product_id)

来自兰德手册

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.
于 2012-06-29T09:21:52.527 回答
1

函数内部的参数RAND(x)是种子,所以你每次都用相同的值播种它。相反,让它保持原样RAND(),它会有所不同。

于 2012-06-29T09:21:08.290 回答
0

使用这种方式:

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

在此处查看手册

于 2012-06-29T09:28:18.577 回答
0

SELECT id, name FROM productsAS prod ORDER BY RAND()LIMIT 5

于 2012-06-29T09:23:36.567 回答
0

您可能想要的只是ORDER BY RAND()而不是ORDER BY RAND(prod.id)- 如果您给 RAND() 一个整数参数,它将用作种子值,因此您将始终获得相同的“随机”值。

有关详细信息,请参阅http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_rand

于 2012-06-29T09:23:40.420 回答