我需要使用MySQL从表中获取可重复的随机行集.我使用MySQL RAND函数使用行的bigint主键作为种子实现了这一点.有趣的是,这产生的数字看起来并不随机.任何人都可以告诉我这里发生了什么以及如何让它正常工作?
select id from foo where rand(id) < 0.05 order by id desc limit 100
Run Code Online (Sandbox Code Playgroud)
在600行中的一个示例中,没有返回单个行.我将select更改为包含"id,rand(id)"并删除rand子句,这是我得到的:
| 163345 | 0.315191733944408 |
| 163343 | 0.814825518815616 |
| 163337 | 0.313726862253367 |
| 163334 | 0.563177533972242 |
| 163333 | 0.312994424545201 |
| 163329 | 0.312261986837035 |
| 163327 | 0.811895771708242 |
| 163322 | 0.560980224573035 |
| 163321 | 0.310797115145994 |
| 163319 | 0.810430896291911 |
| 163318 | 0.560247786864869 |
| 163317 | 0.310064677437828 |
Run Code Online (Sandbox Code Playgroud)
看看有多少0.31xxx行.一点也不随机.
PS:我知道这很慢但在我的应用中,where子句将行数限制为几千.
对所有行使用相同的种子来执行此操作,例如:
select id from foo where rand(42) < 0.05 order by id desc limit 100
Run Code Online (Sandbox Code Playgroud)
请参阅rand()文档,了解它为何如此工作.如果您想要另一组值,请更改种子.