MySQL中如何高效地(不使用子查询)从最大的N条记录中选择一条随机记录?

发布于 2024-08-29 16:35:49 字数 176 浏览 4 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

残龙傲雪 2024-09-05 16:35:49

如果我理解正确,您需要有序结果集中的第 R 行,其中 R 是随机数。如果是这样,那么带有两个参数的 LIMIT 选项似乎就是您想要的选项。第一个参数可以是从1到N的随机数:

SELECT ... order by weight desc limit R,1

我没有安装MySQL,所以无法测试它。所以我不知道 R 是否可以直接使用 RAND() 或者是否必须预先计算。

If I understand correctly, you want the Rth row from an ordered result set where R 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 from 1 to N:

SELECT ... order by weight desc limit R,1

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.

但可醉心 2024-09-05 16:35:49

您应该看一下:

http://akinas.com/pages/en/blog/ mysql_random_row/

对于实现这一点同时避免表扫描有几个建议,包括:

SELECT * FROM `table` WHERE id >= (
        SELECT FLOOR( MAX(id) * RAND()) FROM `table` 
    ) ORDER BY id LIMIT 1;

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:

SELECT * FROM `table` WHERE id >= (
        SELECT FLOOR( MAX(id) * RAND()) FROM `table` 
    ) ORDER BY id LIMIT 1;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文