MySQL中如何高效地(不使用子查询)从最大的N条记录中选择一条随机记录?
select .. from (
Select ... from ... order by weight desc limit N
) order by rand() limit 1
上面每次都需要创建临时表,效率不高,所以不符合条件。
怎样做才正确呢?
select .. from (
Select ... from ... order by weight desc limit N
) order by rand() limit 1
The above needs to create a temporary table each time,which is not efficient,so it doesn't qualify.
How to do it properly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我理解正确,您需要有序结果集中的第 R 行,其中 R 是随机数。如果是这样,那么带有两个参数的 LIMIT 选项似乎就是您想要的选项。第一个参数可以是从
1到N
的随机数:我没有安装MySQL,所以无法测试它。所以我不知道 R 是否可以直接使用 RAND() 或者是否必须预先计算。
If I understand correctly, you want the
Rth
row from an ordered result set whereR
is a random number. If so, then it seems the LIMIT option with two parameters is the one you want. The first parameter could be the random number from1 to N
:I don't have MySQL installed, so I can't test it. So I do not know if R can use RAND() directly or if it would have to be precomputed.
您应该看一下:
http://akinas.com/pages/en/blog/ mysql_random_row/
对于实现这一点同时避免表扫描有几个建议,包括:
You should take a look at:
http://akinas.com/pages/en/blog/mysql_random_row/
There are several suggestions for implementing this while avoiding table scans, including: