abs(random()) % someNumberGreaterThanZero 可以返回零吗?
SELECT foo FROM bar
WHERE id >= (abs(random()) % (SELECT max(id) FROM bar))
LIMIT 1;
我在另一个答案中看到了这一点,作为 ORDER BY random() 的替代方案。我需要确保 id 始终大于零。我必须将 >=
更改为 >
吗?
SELECT foo FROM bar
WHERE id >= (abs(random()) % (SELECT max(id) FROM bar))
LIMIT 1;
I saw this in another answer as an alternative to ORDER BY random(). I need to make sure id
would always be greater than zero. Do I have to change >=
to >
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于当
x
是y
的倍数时,x % y
返回 0,因此答案是“是的,您的表达式可以返回 0”。因此,如果
id
必须大于 0,则需要使用>
而不是>=
。当然,如果模运算符不返回 0,您仍然可以使用>
而不是>=
,并且会得到相同的效果。Since
x % y
returns 0 whenx
is a multiple ofy
, the answer is "Yes, your expression could return 0".So, if
id
must be greater than 0, you need to use>
rather than>=
. Of course, if the modulo operator didn't return 0, you could still use>
instead of>=
and you'd get the same effect.是的。如果
abs(random())
返回max(id)
的值,则模数结果将为零。由于abs(random())
可以返回 0 到 0 之间的任何值。 9223372036854775807,这绝对是可能的。Yes. If
abs(random())
returned the value ofmax(id)
, then the modulo's result would be zero. Sinceabs(random())
can return any value between 0 & 9223372036854775807, this is definitely possible.是的,它可以通过两种方式返回 0
考虑
3 % 3 == 0
、6 % 3 == 0
等。如果随机,您将得到 0 ()
恰好是max(id)
或其偶数除法器。random()
还可以返回 0 和0 % everything == 0
,这是另一种可能性。Yes it can return 0 in two ways
Consider that
3 % 3 == 0
,6 % 3 == 0
, etc. Then you would get 0 ifrandom()
happens to bemax(id)
or an even divider thereof.random()
can also return 0 and0 % anything == 0
, that is the other possibility.是的,应该是>因为模除法可以返回 0(
a mod a ==0
,0 mod a == 0
)。另外,您可能想检查(SELECT max(id)
是否不为 null/0(a mod 0
在某些系统中未定义,或者 a)Yes, it should be > because modulo division can return 0(
a mod a ==0
,0 mod a == 0
). Also, you might want to check if(SELECT max(id)
is not null/0 (a mod 0
is undefined in some systems, or a)