如何使用 SOQL 从force.com 数据库请求单个随机行?
总行数在 10k-100k 行范围内。我可以在force.com 上使用RAND() 吗?不幸的是,尽管所有行都有一个唯一的数字标识符,但仍然存在许多间隙,而且我经常想从过滤的子集中选择一个随机行。
我怀疑没有特别有效的方法可以做到这一点,但是有可能吗?
最终,我想做的就是从表(或基于特定过滤条件的子集)中随机提取一行。
如果force.com不允许我选择随机行,那么我可以查询要从中选择的行,并将顺序ID分配给所有行,例如1-1,035,然后在本地选择该范围内的随机数,例如349,然后得到第349行?
Total row-count is in the range 10k-100k rows. Can I use RAND() on force.com? Unfortunately although all the rows have a unique numeric identifier, there are many gaps, and I'd often want to select a random row from a filtered subset anyway.
I suspect there's no particularly efficient way to do this, but is it possible at all?
Ultimately all I want to do is to extract one row from a table (or a subset based on specific filter criteria) at random.
If force.com doesn't let me select a random row, then can I query the rows to select from, and assign sequential IDs to all the rows, say 1-1,035, and then select a random number in that range locally, say 349, and then get row 349?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 SOQL OFFSET 来选择随机记录。
操作方法如下:
You can use SOQL OFFSET to select a random record.
Here's how you do it:
你可以尝试这样的事情。
使用
Math.random() - 将返回 0 到 1 之间的小数。将其乘以 100 r 1000 即可得到整数。
使用 SOQL 获取该行
SELECT Bar__c, Bar_Seq_Col_c from Foo_c where Bar_Seq_Col__c = :Math.random() * 10
这只是一个示例想法,您可以考虑这些行来看看它是否是一个可行的想法。
You could try something like this.
Use
Math.random() - which will return a decimal ranging between 0 to 1. multiply that by 100 r 1000 to get integer.
use SOQL to fetch that row
SELECT Bar__c, Bar_Seq_Col_c from Foo_c where Bar_Seq_Col__c = :Math.random() * 10
this is just a sample idea you can think of these lines to see is it a feasiable idea.
不,您不能使用 ORDER BY RAND() 或类似的东西。您可以按实际字段排序(可以选择使用
NULLS LAST
等)。您可以使用 LIMIT、GROUP BY 和虽然还有 MIN、MAX、COUNT...也许您可以写更多关于需要显示随机行的目的...否则
ORDER BY LastModifiedDate DESC LIMIT 1
有什么问题?或者选择 100 行并使用 Math.random( ) 或 Crypto.getRandomInteger() 模 100?No, you can't use
ORDER BY RAND()
or something like that. You can sort by real field (optionally withNULLS LAST
etc.). You could use LIMIT, GROUP BY & HAVING though as well as MIN, MAX, COUNT...Maybe if you'd write more about the purpose for which you need to display a random row... Otherwise what's wrong with
ORDER BY LastModifiedDate DESC LIMIT 1
? Or selecting 100 rows and showing random row with Math.random() or Crypto.getRandomInteger() modulo 100?