MySQL 中的 SELECT 整数范围。例如。 1,2,3,4,...,n;
我需要在 MySQL 中选择整数范围。像这样的
SELECT RANGE(10,20) AS range;
返回
10, 11, 12, 13, 14, ..., 20
为什么?强>
我想从尚未注册的范围中选择随机电话号码。这是想法。
SELECT RANGE(100000,999999) AS range FROM Phone WHERE PhoneNum <>;范围限制下限(100000 + RAND()*(899999);
I need to select range of integer in MySQL. Something like this
SELECT RANGE(10,20) AS range;
returns
10, 11, 12, 13, 14, ..., 20
Why?
I would like to select random phone number from range which is not yet registered. This is idea.
SELECT RANGE(100000,999999) AS range FROM phone WHERE phoneNum <> range LIMIT FLOOR(100000 + RAND()*(899999);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的查询存在问题:
range
。它是一个别名,只有在执行 WHERE 子句后才会定义。<>
将一个数字与一组数字进行比较也是没有意义的。一般来说,您可以使用IN(...)
,但在特定情况下,您应该使用BETWEEN 100000 和 999999
并避免需要RANGE函数。
ORDER BY RAND()
。尝试使用此查询:
如果您想查找表中没有的数字,并且可用数字尚未接近耗尽(例如分配的数字少于 80%),一个好的方法是生成随机数并检查它们是否已分配,直到你会发现一个不是。
可能存在纯 MySQL 解决方案,但我认为它需要一些扭曲的连接、随机和模数。
Problems with your query:
range
in the WHERE clause. It is an alias and will only be defined after the WHERE clause is performed.<>
. In general you could useIN(...)
, but in you particular case you should useBETWEEN 100000 and 999999
and avoid the need for aRANGE
function.ORDER BY RAND()
.Try using this query:
If you want to find a number not in your table and the available numbers are not close to depletion (say less than 80% are assigned) a good approach would be to generate random numbers and check if they are assigned until you find one that isn't.
A pure MySQL solution may exists but I think it needs some twisted joins, random and modulus.
另一种选择:
首先创建一个仅包含数字的表,其中包含从 1 到 MAX_NUM 的所有数字。
然后使用这个查询:
这样你也可以通过改变限制值来相对快速地获得多个数字。
An alternative:
First of all create a table with just numbers that has all the numbers from 1 to MAX_NUM.
Then use this query:
This way you can also get multiple number relatively fast by changing the limit value.
目前,MariaDB SEQUENCE 引擎可以为您执行此操作:
Currently the MariaDB SEQUENCE engine can do this for you: