mysql设置整数范围,SELECT在MySQL中的整数范围。例如。 1,2,3,4,...,n;

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);

解决方案

Problems with your query:

You can't use range in the WHERE clause. It is an alias and will only be defined after the WHERE clause is performed.

Even if you could use it, it makes no sense to compare a number with a set of numbers using <>. In general you could use IN(...), but in you particular case you should use BETWEEN 100000 and 999999 and avoid the need for a RANGE function.

If you only want one number then the limit should be 1, not something random. Usually to select random items you use ORDER BY RAND().

Try using this query:

SELECT phoneNum, 100000 as rangeStart, 999999 AS rangeEnd

FROM phone

WHERE phoneNum NOT BETWEEN 100000 AND 999999

ORDER BY RAND()

LIMIT 1

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值